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

    问题:
    1. 为了满足一些只在某种特定情况下才会执行的特殊行为的需要,向原有类中添加新的代码,这样会增加原有类的复杂度,使其变得越来越难以维护,解决方法就是把类的核心职责和装饰功能区分开。
    2. 功能定义完全依赖于继承体系会导致类的数量过多,而且代码会产生重复。装饰模式使用组合和委托而不是只使用继承来解决功能变化的问题。

    实现:
    1. 类图示例:

    2. 代码示例:

    //子对象基类
    abstract class Tile
    {
    	abstract function getWealthFactor();
    }
    //子对象类实现
    class Plains extends Tile
    {
    	private $wealthfactor = 2;
    	public function getWealthFactor()
    	{
    		return $this->wealthfactor;
    	}
    }
    //装饰对象基类
    abstract class TileDecorator extends Tile
    {
    	protected $tile;
    	public function __construct(Tile $tile)
    	{
    		$this->tile = $tile;
    	}
    }
    //装饰对象类实现
    class DiamondDecorator extends TileDecorator
    {
    	public function getWealthFactor()
    	{
    		return $this->tile->getWealthFactor() + 2;
    	}
    }
    //装饰对象类实现
    class PollutionDecorator extends TileDecorator
    {
    	public function getWealthFactor()
    	{
    		return $this->tile->getWealthFactor() - 4;
    	}
    }
    //应用
    $tile = new PollutionDecorator(new DiamondDecorator(new Plains()));
    echo $tile->getWealthFactor();
    

    注:代码运行时,通过将“Plains”组件与“DiamondDecorator”和“PollutionDecorator”两种装饰对象进行合并,从而得到同时具有“DiamondDecorator”和“PollutionDecorator”两种特性的“Plains”组件。

    效果:
    1. 有效地把类的核心职责和装饰功能区分开,降低类复杂度与耦合度。
    2. 类的核心职责与多个装饰功能之间可以按需组合使用,十分灵活。
    3. 因为装饰对象作为子对象的包装,所以保持基类中的方法尽可能少是很重要的。如果一个基类具有大量特性,那么装饰对象就不得不为它们包装的对象的所有public方法加上委托,这会造成代码的耦合。

  • 相关阅读:
    项目上线之期初数据调整
    系统升级时,数据库脚本执行注意事项,血的教训
    数据精度问题的处理
    系统发布说明文档
    SQLServer中数据库文件的存放方式,文件和文件组
    数据库的持续集成和版本控制
    SQL Server 远程链接服务器详细配置【转载】
    批处理中的IF ERRORLEVEL
    asp.net用url重写URLReWriter实现任意二级域名
    关于excel导入access问题(已解决)
  • 原文地址:https://www.cnblogs.com/wujuntian/p/9623407.html
Copyright © 2011-2022 走看看