策略模式-代码

策略模式

定义一族算法类,将每一个算法分别封装起来,让它们能够互相替换。策略模式可使算法的变化独立于使用它们的客户端 (这里的客户端代指使用算法的代码)算法

策略模式分为三部分 策略的定义、建立、使用bash

策略定义:

interface Strategy
{

}

class StrategyA implements Strategy
{
    //策略A
}

class StrategyB implements Strategy
{
    //策略B
}
复制代码

策略建立:

class StrategyFactory
{
    public function getStrategy($type): Strategy
    {
        if ($type == "a") {
            return new StrategyA();
        }
        
        return new StrategyB();
    }
}
复制代码

策略使用:

class OrderService
{
    public function SubOrder($order)
    {
        $strategyType = $order['strategyType'];
        $strategy = StrategyFactory::getStrategy($strategyType);
        //$strategy->doSomething();
    }
}
复制代码

进一步优化

在策略建立时, 若是你想真正的彻底消除, 能够在策略建立实现map表, 根据map表查找进行对象建立. 这时候须要权衡利弊。markdown

相关文章
相关标签/搜索