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

简介:这是php设计模式 Strategy(策略模式)的详细页面,介绍了和php,有关的知识、技巧、经验,和一些php源码等。

class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=337759' scrolling='no'>
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 ?>

爱J2EE关注Java迈克尔杰克逊视频站JSON在线工具

http://biancheng.dnbcw.info/php/337759.html pageNo:9
原文地址:https://www.cnblogs.com/ooooo/p/2247008.html