设置模式之装饰模式
什么事装饰模式呢?其实装饰模式就是为一个对象穿上不同的衣服。
0.64
Code
1abstract class food{
2
3 public $des="食物";
4 public $cost;
5
6 function getDes()
7 {
8 return $this->des;
9 }
10
11 function getCost()
12 {
13 return $this->cost;
14 }
15
16 }
17
18
19 class rice extends food {
20
21 function __construct()
22 {
23 $this->des ="米饭";
24
25 $this->cost="0.44";
26 }
27
28
29
30 }
31
32 class sub extends food{
33
34 public $obj;
35
36 function __construct()
37 {
38
39 }
40 }
41
42 class potato extends sub {
43
44
45
46 function __construct($obj)
47 {
48 $this->obj =$obj;
49 $this->des ="土豆丝";
50 $this->cost =0.10;
51 }
52
53 function getDes()
54 {
55 return $this->obj->getDes().$this->des;
56 }
57
58 function getCost()
59 {
60
61
62 return $this->obj->getCost()+$this->cost;
63 }
64
65 }
66
67 class xiancai extends sub {
68
69
70
71 function __construct($obj)
72 {
73 $this->obj =$obj;
74 $this->des ="咸菜";
75 $this->cost =0.10;
76 }
77
78 function getDes()
79 {
80 return $this->obj->getDes().$this->des;
81 }
82
83 function getCost()
84 {
85 return $this->obj->getCost()+$this->cost;
86 }
87
88 }
89
90
91 $eat = new rice();
92 $eat = new tomoto($eat);
93
94 $eat = new xiancai($eat);
95
96 // print_r($eat);
97
98 echo $eat->getDes();
99
100 echo $eat->getCost();
显示的结果为 米饭土豆丝咸菜1abstract class food{
2
3 public $des="食物";
4 public $cost;
5
6 function getDes()
7 {
8 return $this->des;
9 }
10
11 function getCost()
12 {
13 return $this->cost;
14 }
15
16 }
17
18
19 class rice extends food {
20
21 function __construct()
22 {
23 $this->des ="米饭";
24
25 $this->cost="0.44";
26 }
27
28
29
30 }
31
32 class sub extends food{
33
34 public $obj;
35
36 function __construct()
37 {
38
39 }
40 }
41
42 class potato extends sub {
43
44
45
46 function __construct($obj)
47 {
48 $this->obj =$obj;
49 $this->des ="土豆丝";
50 $this->cost =0.10;
51 }
52
53 function getDes()
54 {
55 return $this->obj->getDes().$this->des;
56 }
57
58 function getCost()
59 {
60
61
62 return $this->obj->getCost()+$this->cost;
63 }
64
65 }
66
67 class xiancai extends sub {
68
69
70
71 function __construct($obj)
72 {
73 $this->obj =$obj;
74 $this->des ="咸菜";
75 $this->cost =0.10;
76 }
77
78 function getDes()
79 {
80 return $this->obj->getDes().$this->des;
81 }
82
83 function getCost()
84 {
85 return $this->obj->getCost()+$this->cost;
86 }
87
88 }
89
90
91 $eat = new rice();
92 $eat = new tomoto($eat);
93
94 $eat = new xiancai($eat);
95
96 // print_r($eat);
97
98 echo $eat->getDes();
99
100 echo $eat->getCost();
0.64