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

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

    1.找出代码中可能变化之处,把他们独立出来,不要和那些不变化的代码混在一起

    2.针对借口编程,而不是针对实现编程

    3.多用组合少用继承

    namespace DesignPatternStrategyPattern;
    
    //定义行为借口
    Interface FlyBehavior { public function fly(); } Interface QuakeBehavior { public function Quake(); }
    //定义鸭子抽象类
    abstract class Duck { protected $fly; protected $quake; public function __construct(FlyBehavior $fly, QuakeBehavior $quake) { $this -> fly = $fly; $this -> quake = $quake; } public function fly() { $this -> fly -> fly(); } public function quake() { $this -> quake -> quake(); } public function setFlyBehavior(FlyBehavior $fly) { $this -> fly = $fly; } public function setQuakeBehavior(QuakeBehavior $quake) { $this -> quake = $quake; } }

    具体实现的分离

    class HomeDock extends Duck
        {
            public function cooked()
            {
                echo "home duck be cooked
    ";
            }
        }
    
        class WildDuck extends Duck
        {
            public function hunter()
            {
                echo "wild duck is hunting
    ";
            }
        }
    
        class FlyPeace implements FlyBehavior
        {
            public function fly()
            {
                echo "fly peace
    ";
            }
        }
    
        class FlyRocket implements FlyBehavior
        {
            public function fly()
            {
                echo "fly like rocket
    ";
            }
        }
    
        class BoomQuake implements QuakeBehavior
        {
            public function quake()
            {
                echo "quake like a boom
    ";
            }
        }
    
        $homedock = new HomeDock(new FlyRocket, new BoomQuake);
        $homedock -> cooked();
        $homedock -> quake();
        $homedock -> fly();
        $homedock -> setFlyBehavior(new FlyPeace);
        $homedock -> fly();

    输出

    home duck be cooked
    quake like a boom
    fly like rocket
    fly peace
  • 相关阅读:
    for是个什么玩意
    面向对象 多态
    面向对象 接口
    面向对象oop
    面向对象基本
    java修饰符的作用范围
    static 关键字介绍
    JsonLayout log4j2 json格式输出日志
    多线程--Thread.join方法
    idea常用实用快捷键
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5548249.html
Copyright © 2011-2022 走看看