php八大设计模式之策略模式
2017-03-28 20:30
477 查看
策略模式提供一个虚拟的整体,根据不同的要求(参数)提供不同的“零件”(调用不同的“零件”实现不同的结果)。
<?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)); ?>
相关文章推荐
- php八大设计模式之策略模式
- PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)
- 【PHP设计模式】策略模式
- PHP设计模式(5)策略模式
- PHP草根论之设计模式-策略模式
- PHP设计模式之:策略模式
- 学习php设计模式 php实现策略模式(strategy)
- PHP设计模式——策略模式
- php 设计模式-策略模式
- PHP设计模式9-策略模式
- PHP设计模式--策略模式
- php设计模式 Strategy(策略模式)
- PHP设计模式之策略模式
- PHP设计模式之策略模式
- PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)
- php设计模式 Strategy(策略模式)
- Php设计模式之【策略模式Strategy Pattern】
- PHP设计模式系列 - 策略模式
- PHP设计模式之策略模式
- PHP设计模式-策略模式