您的位置:首页 > 编程语言 > PHP开发

策略模式

2012-05-29 22:24 267 查看
策略模式的简单实现

<?php
namespace  Strategy;

/**
* 抽象算法类
* @author struggle
* @verison 2012-5-29
*/
abstract class Strategy {
/**
* 算法方法
*/
public abstract function algorithmFunction();
}
/**
* 具体算法类A
* @author struggle
* @verison 2012-5-29
*/
class SpecificStrategyA extends  Strategy {
/**
* 具体算法A的实现
*/
public function algorithmFunction(){
echo '具体算法A<br>';
}
}
/**
* 具体算法类B
* @author struggle
* @verison 2012-5-29
*/
class SpecificStrategyB extends Strategy {
/**
* 具体算法B的实现
*/
public function algorithmFunction(){
echo '具体算法B<br>';
}
}
/**
* 具体算法类C
* @author struggle
* @verison 2012-5-29
*/
class SpecificStrategyC extends  Strategy {
/**
* 具体算法c的实现
*/
public function algorithmFunction() {
echo '具体算法C<br>';
}
}

class Context {
/**
* 算法对象
* @var obj
*/
private $Strategy ;
/**
* 设置算法对象
* @param Strategy $obj
*/
public function setStrategy( Strategy $obj){
$this->Strategy = $obj;
}

public function contextInterface(){
if(!isset($this->Strategy)){
throw new  \Exception('算法对象未设置');
}
$this->Strategy->algorithmFunction();
}
}

$context = new Context();
$context->setStrategy(new SpecificStrategyA());
$context->contextInterface();
$context->setStrategy(new SpecificStrategyB());
$context->contextInterface();
$context->setStrategy(new SpecificStrategyC());
$context->contextInterface();


#使用策略与简单工厂的结合

Context类修改如下:

class Context{
/**
* 算法对象
* @var obj
*/
private $Strategy ;
/**
* 设置算法对象
* @param $obj
*/
public function __construct($type){
switch (strtoupper($type)){ //全部转换为大写
case 'A':
$this->Strategy = new SpecificStrategyA();
break;
case 'B':
$this->Strategy = new SpecificStrategyB();
break;
case 'C':
$this->Strategy = new SpecificStrategyC();
break;
default:
throw new \Exception('未找到算法类 : '.$type);
}
}

public function contextInterface(){
if(!isset($this->Strategy)){
throw new  \Exception('算法对象未设置');
}
$this->Strategy->algorithmFunction();
}
}

$context = new Context('A');
$context->contextInterface();
$context = new Context('B');
$context->contextInterface();
$context = new Context('c');
$context->contextInterface();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 策略模式 Context