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
    ?>
    

      

      

  • 相关阅读:
    #网络流,最小割#洛谷 1344 [USACO4.4]追查坏牛奶Pollutant Control
    #线段树,倒序#CF356A Knight Tournament
    #错排,高精度#洛谷 3182 [HAOI2016]放棋子
    #KMP,dp#洛谷 3426 [POI2005]SZA-Template
    #差分约束系统,Spfa,SLF优化#Hdu 3666 THE MATRIX PROBLEM
    #min_max容斥#Hdu 4336 Card Collector
    #组合计数,卢卡斯定理#D 三元组
    #计数,记忆化搜索#C 连边方案
    #区间dp,离散#D 弱者对决
    #dp#C 公共子序列
  • 原文地址:https://www.cnblogs.com/-beyond/p/8760414.html
Copyright © 2011-2022 走看看