zoukankan      html  css  js  c++  java
  • 装饰器模式

      内容来自《深入PHP面向对象、模式与实践》

      装饰器模式其实和他的名称是一个意思,就是起“装饰的作用”。

      要想起到装饰作用,首先必须有一个原型,这个原型就是要被装饰的对象,这个原型包含一些自身的属性。执行装饰动作的是另外一个对象,目的就是修改原型中的某些属性,让他看起来和以前不一样,因为做了装饰了嘛,但是,原型本身还是没有变,只是装饰之后的返回的样子变了。所以思路就是:一个将原型传递给装饰者,装饰者对原型进行装饰,然后返回经过装饰后的对象。

    <?php
    abstract class Tile{
        abstract function getWealthFactor();
    }
    
    //这就是原型对象,被装饰的对象
    class Plains extends Tile{
        //原型中有一个wealthfactor属性,其他装饰器都是装饰这个属性
        private $wealthfactor = 2;
        function getWealthFactor(){
            return $this->wealthfactor;
        }
    }
    
    //声明一个装饰者抽象接口
    abstract class TileDecorator extends Tile{
        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;
        }
    }
    
    $plains = new Plains();
    echo $plains->getWealthFactor()."
    ";
    //输出2
    
    //将一个原型对象传给一个钻石装饰者,让其进行装饰
    $tile = new DiamondDecorator( new Plains() );
    echo $tile->getWealthFactor()."
    ";
    //输出4
    
    //进行多次的装饰
    $tile = new PollutionDecorator( new DiamondDecorator( new Plains() ) );
    echo $tile->getWealthFactor()."
    ";
    //输出0
    ?>
    

      

      

  • 相关阅读:
    linux基础(一)
    网络基础之网络协议篇
    操作系统简介
    计算机组成原理
    【C#】=>符号的使用
    【Unity3D】用继承EditorUpdater类来实现Editor模式下的后台处理
    【Unity3D】Tags和Layers
    【Unity3D】Unity3D中Material与ShareMaterial引用的区别
    【Unity3D】Unity中用C#读取CSV文件
    【Unity3D】用C#读取INI配置文件
  • 原文地址:https://www.cnblogs.com/-beyond/p/8760414.html
Copyright © 2011-2022 走看看