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();
    
    ?>
  • 相关阅读:
    使用pull解析XML文件
    使用Pull解析器生成XML文件
    Android下文件访问的权限
    Android之SharedPreference存储数据
    Android之外部存储(SD卡)
    Android的内部存储
    Android数据存储的方式
    点击事件的四种写法
    Context
    EclipseADT编写单元测试代码的步骤
  • 原文地址:https://www.cnblogs.com/mtima/p/3186034.html
Copyright © 2011-2022 走看看