您的位置:首页 > 其它

策略模式

2015-06-26 14:52 141 查看
/**
* 策略抽象类 规定策略名称
*/
abstract class strategy {
abstract function operating();
}
/**
* 第一个策略
*/
class strategy_1 extends strategy {
public function operating() {
echo '第一个策略';
}
}
/**
* 第二个策略
*/
class strategy_2 extends strategy {
public function operating() {
echo'第二个策略';
}
}

/**
* 策略生成器
*/
class strategy_context {
private $strategy;
public function __construct($num) {
//根据不同的条件生成不同的策略
if($num == 1) {
$this->strategy = new strategy_1();
}else{
$this->strategy = new strategy_2();
}
}
public function operating() {
return $this->strategy->operating();
}
}

$strategy_context = new strategy_context(1);
$strategy_context->operating();


策略模式(strategy):
它定义了算法家族,分别将各个算法封装起来,让各个算法之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户端。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: