php八大设计模式之策略模式

   策略模式提供一个虚拟的整体,根据不同的要求(参数)提供不同的“零件”(调用不同的“零件”实现不同的结果)。
<?php
    /**
     * 策略模式
     *    跟工厂模式差别不大,用到谁就去实例化谁。
     *
     * 工厂模式,着眼于得到对象,并操作对象。
     * 策略模式,着重得到对象某方法的运行结果。
    */
    //计算器接口。
    interface Math{
        public function calc($op1,$op2);
    }
    //乘法类。
    class MathMul implements Math{
        public function calc($op1,$op2){
            return $op1*$op2;
        }
    }
    //除法类。
    class MathDiv implements Math{
        public function calc($op1,$op2){
            return $op1/$op2;
        }
    }
    加法类。
    class MathAdd implements Math{
        public function calc($op1,$op2){
            return $op1+$op2;
        }
    }
    减法类。
    class MathDel implements Math{
        public function calc($op1,$op2){
            return $op1-$op2;
        }
    }
    //我们将这些类组装起来,形成一个对外的虚拟计算器。
    class CMath{
        protected $calc=null;
        public function __construct($type){
            $type="Math".$type;
            $this->calc=new $type;
        }
        public function getNum($op1,$op2){
            return $this->calc->calc($op1,$op2);
        }
    }
    //模拟前台的运算符。
    $arr=['Add','Del','Div','Mul'];
    shuffle($arr);
    $pop=array_pop($arr);
    //根据运算符拿到计算结果。
    $c=new CMath($pop);
    echo $c->getNum($o=rand(1,100),$p=rand(1,100));
?>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值