php设计模式课程---6、策略模式如何使用
一、总结
一句话总结:比如代码需求,做一饭店,有南北方不同菜系,不同分店有不同的饭菜汤的需求,代码怎么设计
从饭店有特色过渡到厨师有特色(南方厨师(南方饭,南方菜,南方汤),北方厨师(北方饭,北方菜,北方汤))
利用厨师的组合实现饭店有不同特色(满足不同分店的需求)
1、传入的参数是对象,执行对象的方法如何实现?
83 class FD { 84 protected $fanCreateor = null; 85 protected $caiCreateor = null; 86 protected $tangCreateor = null; 87 88 public function __construct($f,$c,$t) { 89 $this->fanCreateor = $f; 90 $this->caiCreateor = $c; 91 $this->tangCreateor = $t; 92 } 93 94 public function createFan() { 95 return $this->fanCreateor->fan(); 96 } 97 98 public function createCai() { 99 return $this->caiCreateor->cai(); 100 } 101 102 public function createTang() { 103 return $this->tangCreateor->tang(); 104 } 105 } 106 107 108 $fd = new FD(new NorthCook() , new NorthCook() , new SouthCook);
2、编程的灵活性原则?
有什么 比 是什么 更灵活
组合 比 继承更灵活
二、策略模式如何使用
1、代码
1 <?php 2 /* 3 // 做一饭店 4 class FanDian { 5 public function fan() { 6 return '面条'; 7 } 8 9 public function cai() { 10 return '炒菜'; 11 } 12 13 public function tang() { 14 return '蛋花汤'; 15 } 16 } 17 18 19 class SouthDian { 20 public function fan() { 21 return '大米饭'; 22 } 23 24 public function cai() { 25 return '烧菜+奶油'; 26 } 27 28 public function tang() { 29 return '海鲜汤'; 30 } 31 } 32 33 34 class BjDian { 35 public function fan() { 36 return '大米饭'; 37 } 38 39 public function cai() { 40 return '炒菜'; 41 } 42 43 public function tang() { 44 return null; 45 } 46 } 47 48 49 50 $fd = new FanDian(); 51 echo $fd->tang(); 52 53 */ 54 55 class NorthCook { 56 public function fan() { 57 return '面条'; 58 } 59 60 public function cai() { 61 return '炒菜'; 62 } 63 64 public function tang() { 65 return '蛋花汤'; 66 } 67 } 68 69 class SouthCook { 70 public function fan() { 71 return '米饭'; 72 } 73 74 public function cai() { 75 return '烧菜+奶油'; 76 } 77 78 public function tang() { 79 return '海鲜汤'; 80 } 81 } 82 83 class FD { 84 protected $fanCreateor = null; 85 protected $caiCreateor = null; 86 protected $tangCreateor = null; 87 88 public function __construct($f,$c,$t) { 89 $this->fanCreateor = $f; 90 $this->caiCreateor = $c; 91 $this->tangCreateor = $t; 92 } 93 94 public function createFan() { 95 return $this->fanCreateor->fan(); 96 } 97 98 public function createCai() { 99 return $this->caiCreateor->cai(); 100 } 101 102 public function createTang() { 103 return $this->tangCreateor->tang(); 104 } 105 } 106 107 108 $fd = new FD(new NorthCook() , new NorthCook() , new SouthCook); 109 110 echo $fd->createFan() , "<br>"; 111 echo $fd->createTang() , "<br />"; 112 113 114 115 ?>