zoukankan      html  css  js  c++  java
  • 策略模式

    策略模式:定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

    类结构图:

    策略模式类图

    php代码实现:

    <?php
    class CashSuper{
        function AcceptCash($money){
            return 0;
        }
    }
    class CashNormal extends CashSuper{
        function AcceptCash($money){
            return $money;
        }
    }
    class CashRebate extends CashSuper{
        public $discount = 0;
        function __construct($ds){
            $this -> discount = $ds;
        }
        function AcceptCash($money){
            return $money * $this -> discount;
        }
    
    }
    class  CashReturn extends CashSuper{
        public $total = 0, $ret = 0;
        function __construct($t, $r){
            $this -> total = $t;
            $this -> ret = $r;
        }
        function AcceptCash($money){
            if($money >= $this->total){
                return $money - $this -> ret;
            }else{
                return $money;
            }
        }
    }
    class CashContext{
        function __construct($csuper){
            $this -> cs = $csuper;
        }
        function GetRequest($money){
            return $this -> cs -> AcceptCash($money);
        }
    }
    
    fwrite(STDOUT, "money: ");
    $money = trim(fgets(STDIN));
    $strategy = array();
    $strategy['1'] = new CashContext(new CashNormal());
    $strategy['2'] = new CashContext(new CashRebate(0.8));
    $strategy['3'] = new CashContext(new CashReturn(300,100));
    fwrite(STDOUT, "type:[1]for normal,[2]for 80% discount [3]for 300 -100.");
    $ctype = trim(fgets(STDIN));
    if(array_key_exists($ctype,$strategy)){
        $cc = $strategy[$ctype];
    }else{
        fwrite(STDOUT, "Undefine type.Use normal mode.");
        $cc = $strategy["1"];
    }
    echo $cc -> GetRequest($money);
    
    ?>
    

      

  • 相关阅读:
    php中的heredoc和nowdoc对比
    PHP官方网站及PHP手册
    php扩展编译方法
    linux下修改时间和时区
    个人觉得非常好用的mysql客户端工具HeidiSQL
    mysql主从复制总结
    mysql优化的21条经验(转)
    mysql存储引擎选择(转)
    show profiles 分析sql耗时瓶颈
    tar命令的使用方法
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4232093.html
Copyright © 2011-2022 走看看