• php设计模式 -- 策略模式


    策略模式(Strategy pattern)是行为类模式中的一个类型。行为类模式用来说明一个应用是如何运作的。

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

    根据情况传入特定的参数,执行特定的算法,返回特定的数据。

    • 封装:把行为用接口封装起来,我们可以把那些经常变化的部分,从当前的类中单独取出来,用接口进行单独的封装。
    • 互相替换:我们封装好了接口,通过指定不同的接口实现类进行算法的变化。
    <?php
    /**
     * 定义接口
     */
    interface car{
        public function run();
    }
    
    /**
     * 接口算法实现
     * @return [type] [description]
     */
    class bmwCar implements car{
        public function run(){
    
            echo "宝马汽车在路上奔驰
    ";
        }
    }
    
    /**
     * 接口算法实现
     * @return [type] [description]
     */
    class audiCar implements car{
        public function run(){
    
            echo "奥迪汽车在路上奔驰
    ";
        }
    }
    
    /**
     * 使用不同算法的类
     * @param integer $speed [description]
     */
    class chooseCar{
        public $speed;
    
        function __construct($speed=60){
            $this->speed = $speed;
    
        }
    
        function start($brand){
            $car = null;
    
            switch($brand){
                case "bmw":
                    $car = new bmwCar();
                    break;
                case "audi":
                    $car = new audiCar();
                    break;
                default:
                    $car = new bmwCar();
            }
            $car->run();
            echo "时速为{$this->speed}km/h";
        }
    }
    
    $car = new chooseCar(180);
    $car->start("audi");
    
    //输出
    奥迪汽车在路上奔驰 时速为180km/h
  • 相关阅读:
    Orchard part8
    最有效地优化 Microsoft SQL Server 的性能
    MSSQL优化之索引优化
    Orchard使用中的坎坎坷坷
    GridView----CustomRowCellEdit 使用注意事项
    VS 编辑并继续(转载)
    Visual Studio 2010(.NET 4.0)中使用SQLite.NET
    .net环境下ckeditor与ckfinder中文文件链接乱码的问题
    jQuery常用方法集锦
    checkbox、select、radio的设置与获取
  • 原文地址:https://www.cnblogs.com/mmmzh/p/10107192.html
Copyright © 2020-2023  润新知