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

    <?php
    interface FlyBehavior{
        public function fly();
    }
     
    class FlyWithWings implements FlyBehavior{
        public function fly(){
            echo "Fly With Wings ";
        }
    }
     
    class FlyWithNo implements FlyBehavior{
        public function fly(){
            echo "Fly With No Wings ";
        }
    }
    class Duck{
        private $_flyBehavior;
        public function performFly(){
            $this->_flyBehavior->fly();
        }
     
        public function setFlyBehavior(FlyBehavior $behavior){
            $this->_flyBehavior = $behavior;
        }
    }
     
    class RubberDuck extends Duck{
    }
    // Test Case
    $duck = new RubberDuck();
     
    /*  想让鸭子用翅膀飞行 */
    $duck->setFlyBehavior(new FlyWithWings());
    $duck->performFly();           
     
    /*  想让鸭子不用翅膀飞行 */
    $duck->setFlyBehavior(new FlyWithNo());

    $duck->performFly();

  • 相关阅读:
    CPP STL学习笔记
    CPP 设计模式学习
    blackarch 安装指南
    通过 Http 请求获取 GitHub 文件内容
    实践
    升级
    部署-MySql 之Linux篇
    数据库
    RxJs
    Vue
  • 原文地址:https://www.cnblogs.com/yangtzewang/p/5789621.html
Copyright © 2011-2022 走看看