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对象的计算费用方式

  • 相关阅读:
    Linux新手入门:通过chmod改变文件权限
    Android Activity 以及 Application 生命周期
    java 并发库之 Executors
    java Netty tcp通讯
    Android App 切换语言
    java svg转png
    高效的数独算法-位运算
    Android 高效的`InjectView – ButterKnife`
    Android 监听文件夹
    Android 更新UI
  • 原文地址:https://www.cnblogs.com/TzSteady/p/8562955.html
Copyright © 2011-2022 走看看