设计模式——职责链模式
时间:2010-09-02 来源:yzxlyd
简介:
这个是关于请假、加薪的例子。
职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
需要注意的是:一个请求极有可能到了链的的末端都得不到处理,需要事先考虑全面。
一、UML图
二、代码
1 class Request {2 public $type;
3 public $content;
4 public $num;
5 }
6
7 abstract class Manager {
8 protected $name;
9 protected $superior = NULL;
10 public function __construct($name) {
11 $this->name = $name;
12 }
13 public function SetSuperior($superior) {
14 $this->superior = $superior;
15 }
16 abstract function RequestApplications(Request $request);
17 }
18
19 class CommonManager extends Manager {
20 public function RequestApplications(Request $request) {
21 if ($request->type == '请假' && $request->num <= 2) {
22 echo "{$this->name}:{$request->content} 数量{$request->num} 被批准\n";
23 } else {
24 if (NULL !== $this->superior) {
25 $this->superior
26 ->RequestApplications($request);
27 }
28 }
29 }
30 }
31
32 class GeneralManage extends Manager {
33 public function RequestApplications(Request $request) {
34 if ($request->type == '请假') {
35 echo "{$this->name}:{$request->content} 数量{$request->num} 被批准\n";
36 } elseif ($request->type == '加薪' && $request->num <= 500) {
37 echo "{$this->name}:{$request->content} 数量{$request->num} 被批准\n";
38 } elseif ($request->type == '加薪' && $request->num > 500) {
39 echo "{$this->name}:{$request->content} 数量{$request->num} 再说吧\n";
40 }
41 }
42 }
43
44 $jinli = new CommonManager('经理');
45 $zhongjingli = new GeneralManage('总经理');
46 $jinli->SetSuperior($zhongjingli);
47
48 // 请假
49 $request = new Request();
50 $request->type = '请假';
51 $request->content = '小菜请假';
52 $request->num = 1;
53 $jinli->RequestApplications($request);
54 $request->num = 4;
55 $jinli->RequestApplications($request);
56
57 // 加薪
58 $request->type = '加薪';
59 $request->content = '小菜请求加薪';
60 $request->num = 500;
61 $jinli->RequestApplications($request);
62 $request->num = 1000;
63 $jinli->RequestApplications($request);
相关阅读 更多 +