• [php]php设计模式 Strategy(策略模式)


    1 <?php
    2 /**
    3 * 策略模式(Strategy.php)
    4 *
    5 * 定义一系列算法,把它们一个个封装起来,并且使它们可相互替换,使用得算法的变化可独立于使用它的客户
    6 *
    7 */
    8
    9 // ---以下是一系列算法的封闭----
    10 interface CacheTable
    11 {
    12 publicfunction get($key);
    13 publicfunction set($key,$value);
    14 publicfunction del($key);
    15 }
    16
    17 // 不使用缓存
    18 class NoCache implements CacheTable
    19 {
    20 publicfunction __construct(){
    21 echo"Use NoCache<br/>";
    22 }
    23
    24 publicfunction get($key)
    25 {
    26 returnfalse;
    27 }
    28
    29 publicfunction set($key,$value)
    30 {
    31 returntrue;
    32 }
    33
    34 publicfunction del($key)
    35 {
    36 returnfalse;
    37 }
    38 }
    39
    40 // 文件缓存
    41 class FileCache implements CacheTable
    42 {
    43 publicfunction __construct()
    44 {
    45 echo"Use FileCache<br/>";
    46 // 文件缓存构造函数
    47 }
    48
    49 publicfunction get($key)
    50 {
    51 // 文件缓存的get方法实现
    52 }
    53
    54 publicfunction set($key,$value)
    55 {
    56 // 文件缓存的set方法实现
    57 }
    58
    59 publicfunction del($key)
    60 {
    61 // 文件缓存的del方法实现
    62 }
    63 }
    64
    65 // TTServer
    66 class TTCache implements CacheTable
    67 {
    68 publicfunction __construct()
    69 {
    70 echo"Use TTCache<br/>";
    71 // TTServer缓存构造函数
    72 }
    73
    74 publicfunction get($key)
    75 {
    76 // TTServer缓存的get方法实现
    77 }
    78
    79 publicfunction set($key,$value)
    80 {
    81 // TTServer缓存的set方法实现
    82 }
    83
    84 publicfunction del($key)
    85 {
    86 // TTServer缓存的del方法实现
    87 }
    88 }
    89
    90 // -- 以下是使用不用缓存的策略 ------
    91 class Model
    92 {
    93 private$_cache;
    94 publicfunction __construct()
    95 {
    96 $this->_cache =new NoCache();
    97 }
    98
    99 publicfunction 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 publicfunction __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 ?>
  • 相关阅读:
    使用Beautiful Soup扒取指定标题
    平时笔记
    2017年暑期大数据培训小记
    ZoomIt的使用方法
    ASP.NET使用富文本控件KindEditor(一步到位,亲测有效)
    ASP.NET使用Ajax返回Json对象
    Python简易爬虫
    Class.forName()用法详解
    【4-1】js函数、事件、补充知识
    【3-30】document获取、事件、标记样式
  • 原文地址:https://www.cnblogs.com/bluefrog/p/2078046.html
Copyright © 2020-2023  润新知