zoukankan      html  css  js  c++  java
  • 组合模式

    <?php
    abstract class Lesson{
        private $duration;
        private $costStrategy;
    
        function __construct( $duration, CostStrategy $strategy)
        {
            $this->duration = $duration;
            $this->costStrategy = $strategy;
        }
    
        function cost()
        {
            return $this->costStrategy->cost( $this );
        }
    
        function chargeType()
        {
            return $this->costStrategy->chargeType( $this );
        }
    
        function getDuration()
        {
            return $this->duration;
        }
    }
    
    class Lecture extends Lesson{
        //lecrure 特定的方法
    }
    
    class Seminar extends Lesson{
        //seminar 特定的方法
    }
    
    abstract class CostStrategy{
        abstract function cost( Lesson $lesson);
        abstract function chargeType();
    }
    
    //以下有不同的计费方式

    class TimedCostStrategy extends CostStrategy{
      //计费方式一
    function cost( Lesson $lesson) { return $lesson->getDuration()*5; } function chargeType() { return "hourly rate"; } } class FixedCostStrategy extends CostStrategy{
      //计费方式二
    function cost( Lesson $lesson) { return 30; } function chargeType() { return "fixed rate"; } }

    $lessons[] = new Seminar(4, new TimedCostStrategy() );
    $lessons[] = new Lecture(4, new FixedCostStrategy() );
    foreach ($lessons as $lesson) {
    print " lesson charge {$lesson->cost}";
    print " Charge type: {$lesson->chargeType()} ";
    }



    通过传递不同的CostStrategy对象,来改变Lesson对象的计算费用方式

  • 相关阅读:
    覆盖率测试工具gcov的前端工具_LCOV
    LTE切换与TAU问题
    LTE 切换过程中的数据切换
    TCP数据流稳定性--TCP分片,重组及乱序
    【Android
    【Android
    【Android
    【RN
    【RN
    【RN
  • 原文地址:https://www.cnblogs.com/TzSteady/p/8562955.html
Copyright © 2011-2022 走看看