听老歌 发表于 2011-06-11 15:05

php设计模式 Strategy(策略模式)

   
php设计模式 Strategy(策略模式)1 <?php
2 /**
3* 策略模式(Strategy.php)
4*
5* 定义一系列算法,把它们一个个封装起来,并且使它们可相互替换,使用得算法的变化可独立于使用它的客户
6*
7*/
8
9 //---以下是一系列算法的封闭----
10 interface CacheTable
11 {
12      public function get($key);
13      public function set($key,$value);
14      public function del($key);
15 }
16
17 // 不使用缓存
18 class NoCache implements CacheTable
19 {
20   public function __construct(){
21         echo "Use NoCache<br/>";
22   }
23
24   public function get($key)
25   {
26         return false;
27   }
28
29   public function set($key,$value)
30   {
31         return true;
32   }
33
34   public function del($key)
35   {
36         return false;
37   }
38 }
39
40 // 文件缓存
41 class FileCache implements CacheTable
42 {
43   public function __construct()
44   {
45         echo "Use FileCache<br/>";
46         // 文件缓存构造函数
47   }
48
49   public function get($key)
50   {
51         // 文件缓存的get方法实现
52   }
53
54   public function set($key,$value)
55   {
56          // 文件缓存的set方法实现
57   }
58
59   public function del($key)
60   {
61          // 文件缓存的del方法实现
62   }
63 }
64
65 // TTServer
66 class TTCache implements CacheTable
67 {
68   public function __construct()
69   {
70         echo "Use TTCache<br/>";
71         // TTServer缓存构造函数
72   }
73
74   public function get($key)
75   {
76         // TTServer缓存的get方法实现
77   }
78
79   public function set($key,$value)
80   {
81          // TTServer缓存的set方法实现
82   }
83
84   public function del($key)
85   {
86          // TTServer缓存的del方法实现
87   }
88 }
89
90 // -- 以下是使用不用缓存的策略 ------
91 class Model
92 {
93   private $_cache;
94   public function __construct()
95   {
96         $this->_cache = new NoCache();
97   }
98
99   public function setCache($cache)
100   {
101         $this->_cache = $cache;
102   }
103 }
104
105 class UserModel extends Model
106 {
107 }
108
109 class PorductModel extends Model
110 {
111   public function __construct()
112   {
113         $this->_cache = new TTCache();
114   }
115 }
116
117 // -- 实例一下 ---
118 $mdlUser = new UserModel();
119 $mdlProduct = new PorductModel();
120 $mdlProduct->setCache(new FileCache()); // 改变缓存策略
121 ?>

辣椒封 发表于 2011-06-11 23:06

火速围观!牛人招PHP技术员-出得厅堂,下得厨房,进得洞房!有木有!!有木有!!

http://bbs.phpchina.com/thread-214382-1-1.html   这公司太有才了,做PHP的还要求会武功,找金庸大师学学吧,笑死俺了哈

亮图标 发表于 2011-06-12 16:22

火速围观!牛人招PHP技术员-出得厅堂,下得厨房,进得洞房!有木有!!有木有!!

http://bbs.phpchina.com/thread-214382-1-1.html   这公司太有才了,做PHP的还要求会武功,找金庸大师学学吧,笑死俺了哈
页: [1]
查看完整版本: php设计模式 Strategy(策略模式)