设计模式学习(一)、策略模式

1.策略模式的概念:

定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变法独立于使用算法的客户。

2.策略模式的结构图

3.策略模式角色说明

抽象策略(startegy)角色:定义了支持算法的公共接口。通常使用一个接口或者抽象来实现。环境(Context)角色使用这个接口调用具体策略(ConcreteStrategy)角色定义的算法。
具体策略(ConcreteStartegy)角色:以抽象策略(Strategy)接口实现某具体算法。
环境(Context)角色:持有一个Strategy类的引用,用一个ConcreteStrategy对象来配置。

4.策略模式的实现

比如说Joe公司模拟鸭子游戏,需要让鸭子飞(并非所有的鸭子都回飞),这种场景就可以使用策略模式实现:

<?php
/**
 * 策略模式实例
 */
//抽象策略角色《为接口或者抽象类,给具体策略类继承》
interface Strategy
{
    public function fly();
}

//具体策略角色-用翅膀飞
class FlyWithWings implements Strategy
{
    public function fly()
    {
        echo 'fly with wings';
    }
}

//具体策略角色-不会飞
class FlyNoWay implements Strategy
{

    public function fly()
    {
        echo 'fly no way';
    }

}
 //具体策略角色-坐热气球飞

 class FlyWithFireBubble implements Strategy
{

    public function fly()
    {
        echo 'fly with fire bubble';
    }
}
class Duck
{
    //
}
//环境角色实现类
class SuperDuck extends Duck
{
    //具体策略对象
    private $strategyInstance;

    //构造函数
    public function __construct()
    {
        $this->strategyInstance = new FlyWihtFireBubble();
    }

    public function fly()
    {
        return $this->strategyInstance->fly();
    }
}

//客户端使用
$p = new SuperDuck();

$p->fly();

 

posted on 2016-10-17 15:33  会学习的猪  阅读(172)  评论(0编辑  收藏  举报

导航