zoukankan      html  css  js  c++  java
  • Decorator模式

    <?php
    /**
     * 装饰者模式
     * 装饰者以横向增长的方式扩展类的功能,
     * 而不是以继承的方式纵向扩展类的功能,
     * 从而有效防止继承的子类爆炸式的增多。
     * 来自<<深入PHP,面向对象,模式与实践>>
     */
    
    abstract class Tile {
        abstract function getWealthFactor();
    }
    
    class Plains extends Tile{
        private $wealthfactor = 2;
        
        public function getWealthFactor() {
            return $this->wealthfactor;
        }
    }
    
    //<--------------使用继承--------------->
    class DiamondPlains extends Plains {
        function getWealthFactor() {
            return parent::getWealthFactor() + 2;
        }
    }
    
    class PollutedPlains extends Plains {
        function getWealthFactor() {
            return parent::getWealthFactor() - 4;
        }
    }
    
    //获取diamond和polluted的健康系数
    $diamond = new DiamondDecorator();
    $diamondHealth = $diamond->getWealthFactor();
    
    $polluted = new PollutedPlains();
    $pollutedHealth = $polluted->getWealthFactor();
    
    //<--------------使用装饰者--------------->
    //装饰者超类
    class TileDecorator {
        protected $tile;
        //获取需要装饰的对象。
        function __construct(Tile $tile) {
            $this->tile = $tile;
        }
    }
    
    class DiamondDecorator extends TileDecorator{
        function getWealthFactor() {
            return $this->tile->getWealthFactor() + 2;
        }
    }
    
    class PollutionDecorator extends TileDecorator{
        function getWealthFactor() {
            return $this->tile->getWealthFactor() - 4;
        }
    }
    
    //获取diamond和polluted的健康系数
    //获取diamond装饰的tile对象的健康系数
    $diamond = new DiamondDecorator(new Tile);
    $diamondHealth = $diamond->getWealthFactor();
    
    //获取polluted装饰的tile对象的健康系数
    $polluted = new PollutionDecorator(new Tile);
    $pollutedHealth = $polluted->getWealthFactor();
    
    ?>
  • 相关阅读:
    隐私保护政策
    童真儿童简笔画
    方块十字消
    iOS 判断一断代码的执行时间(从网上看的,自己实现一下)
    iOS BLOCK回调:(妖妖随笔)
    typedef struct
    #define和预处理指令
    UIActivityIndicatorView
    Expected a type 的错误
    iOS 本地化字符串—(妖妖随笔)
  • 原文地址:https://www.cnblogs.com/mtima/p/3186034.html
Copyright © 2011-2022 走看看