zoukankan      html  css  js  c++  java
  • 策略模式

    策略模式

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

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

    使用场景:

    一个电商网站的广告位要根据性别展示不同的广告,硬编码的话就是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.多用组合,少用继承;
  • 相关阅读:
    脏矩形(高效绘图 13.3)
    矢量图形(高效绘图 13.2)
    软件绘图(高效绘图 13.1)
    Instruments(性能调优 12.3)
    测量,而不是猜测(性能调优 12.2)
    CPU VS GPU(性能调优 12.1)
    物理模拟(基于定时器的动画 11.2)
    RHEL Server 6.3下MySQL5.5.25a源码安装
    Linux rpm 命令参数使用详解
    db2 用户权限
  • 原文地址:https://www.cnblogs.com/leezhxing/p/4166869.html
Copyright © 2011-2022 走看看