苏州安居客淞泽家园:常用设计模式之策略模式

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 16:25:12
策略模式(Strategy Pattern):         定义:策略模式指的是程序中涉及决策控制的一种模式。策略模式定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。在策略模式下,在客户端调用这些算法的时候能够使它们互不影响的变化。        在策略模式中,算法是从复杂类提取的,因而可以方便的替换。策略模式通常定义一个抽象的基类,然后根据情况的不同创建不同的类继承这个基类。        示例代码: abstract class Strategy {
    protected $name = "张老三";
    abstract function OnTheWay();
} class WalkStrategy extends Strategy {
    function OnTheWay() {
        echo $this->name . "在路上步行";
    }
} class BicycleStrategy extends Strategy {
    function OnTheWay() {
        echo $this->name . "在路上骑自行车";
    }
} class VehicleStrategy extends Strategy {
    function OnTheWay() {
        echo $this->name . "在路上开汽车";
    }
} class Context {
    private static $instance = null;
   
    private function __construct() {}
   
    public static function getInstance() {
        if(self::$instance == null) {
            self::$instance = new Context();
        }
        return self::$instance;
    }
   
    public function find($strategy) {
        $strategy->OnTheWay();
    }
} $ct = Context::getInstance();
$ct->find(new VehicleStrategy());
echo "
";
$ct->find(new WalkStrategy());
echo "
";
$ct->find(new BicycleStrategy());
?>         上述代码中,Context类中定义了一个成员函数find(),该函数的功能是用来选择具体使用哪个策略。这些策略的功能由IStrategy接口定义,并且该接口有3个实现,分别为WalkStrategy类、BicycleStrategy类和VehicleStrategy类。        策略模式的类关系图:        策略模式的运行结果: