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();
    
    ?>
  • 相关阅读:
    Linxu指令--date,cal
    Linux指令--diff
    Linux指令--ln
    Linux指令--rcp,scp
    Linux指令--telnet
    Linux指令--traceroute,netstat,ss
    Linux指令--ping
    Linux指令--route
    Linux指令--ifconfig
    Linux指令--性能监控和优化命令相关指令
  • 原文地址:https://www.cnblogs.com/mtima/p/3186034.html
Copyright © 2011-2022 走看看