策略模式

策略模式

帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法。

将一组特定的行为和算法封装成类,以适应某些特定的上下文环境。

使用场景:

一个电商网站的广告位要根据性别展示不同的广告,硬编码的话就是if(男士){}else(女士){},使用策略模式可以避免在类中出现逻辑判断。

一个数据输出类,原来只有json格式,后来要求有xml格式,可以用策略模式导出不同格式的数据

 
策略模式的实现:
<?php


interface StrategyInterface
{
    public function doSomething();
}

class StrategyA implements StrategyInterface
{
    public function doSomething()
    {
        // Do something.
    }
}

class StrategyB implements StrategyInterface
{
    public function doSomething()
    {
        // Do something.
    }
}

class Context
{
    private $strategy = null;
/** * @param StrategyInterface $strategy */ public function __construct(StrategyInterface $strategy) //依赖抽象 { $this->strategy = $strategy; } /** * Do something with the Strategy. */ public function doSomething() { $this->strategy->doSomething(); } } $contextA = new Context(new StrategyA()); $contextA->doSomething(); $contextB = new Context(new StrategyB()); $contextB->doSomething();

总结:

总的来说,我们在开发中的设计原则如下:
1.找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起;
2.针对接口编程,不针对实现编程;
3.多用组合,少用继承;
原文地址:https://www.cnblogs.com/leezhxing/p/4166869.html