其他分享
首页 > 其他分享> > 【设计模式】装饰模式

【设计模式】装饰模式

作者:互联网

装饰模式的特点

适用场景

    在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。毕竟客户程序依赖的仅仅是IComponent接口,至于这个接口被做过什么装饰只有实施装饰的对象才知道,而客户程序只负责根据IComponent的方法调用。
    屏蔽某些职责,也就是在套用某个装饰类型的时候,并不增加新的特征,而只把既有方法屏蔽。
    避免出现为了适应变化而子类膨胀的情况。

例如:字体的加粗 和撤销、给人体换装备、多重加密。


缺点

装饰模式虽然提供了比继承更加灵活的扩展方案,但也存在一些缺点:

    开发阶段需要编写很多ConcreteDecorator类型。
    行态动态组装带来的结果就是排查故障比较困难,从实际角度看,最后 IComponent的类型是最外层ConcreteDecorator的类型,但它的执行过程是一系列ConcreteDecorator处理后的结果,追踪和调试相对困难。

装饰器模式的结构与实现

通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关系来创建一个包装对象(即装饰对象)来包裹真实对象,并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰器模式的目标。下面来分析其基本结构和实现方法。

 模式的结构

装饰器模式主要包含以下角色。

  1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
  2. 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。
  3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。


装饰器模式的结构图如图 1 所示。

 

 

为什么半透明模式不能对同一对象进行多次装饰

掐准透明模式中的装饰者具体实现类中对于抽象构件方法的实现,
Component component,componentSB,componentBB; //全部使用抽象构件定义
component = new Window();
componentSB = new ScrollBarDecorator(component);
componentBB = new BlackBorderDecorator(componentSB);
componentBB.display();
这是透明模式:当调用componentBB的display方法的时候,会接着调用componentSB里的display方法,然后调用component里的display方法,这里面是有个大前提的,就是display是最开始抽象构件里就有的方法。
但是你反观半透明模式,调用的方法已经不是最开始抽象构件里就有的方法了,是它自己后面新增的方法了,已经不满足这个大前提了,所以自然不能实现对同一对象的多次装饰。
Document  doc; //使用抽象构件类型定义
doc = new PurchaseRequest();
Approver newDoc; //使用具体装饰类型定义
newDoc = new Approver(doc);

半透明模式强调的是调用新增的方法,用具体的装饰类型来定义装饰之后的对象。
 

动态撤销功能

在实际场景中,除了动态增加功能,往往还需要动态撤销某些功能,假设用装饰模式来实现英雄联盟中英雄购买装备的过程,买一件装备,就相当于动态为英雄增加功能,但如果后期升级装备需要卖掉一件现有的准备时,在实现上就涉及到这件装备功能的卸载。
在比如前面代码中的文字处理功能,字体加粗后可以撤销,字体的颜色也支持更换,也需要功能的动态撤销,接上面的例子,实现撤销的功能需要结合后面会学到的状态模式,新增IState接口,引入了状态的概念
支持撤销功能的代码如下:

//引入了状态的概念
public interface IState
{
    bool Equals(IState newState);
}

//字体是否加粗可以用bool来表示
public class BoldState : IState
{
    public bool IsBold;
    public bool Equals(IState newState)
    {
        if (newState == null)
        {
            return false;
        }
        return ((BoldState)newState).IsBold == IsBold;
    }
}

//字体颜色的状态比较多
public class ColorState : IState
{
    public Color Color = Color.Black;
    public bool Equals(IState newState)
    {
        if (newState == null)
        {
            return false;
        }
        return ((ColorState)newState).Color == Color;
    }
}

//基本功能
public interface IText
{
    string Content { get; }
}

public class TextObject : IText
{
    public string Content { get { return "hello"; } }

}

//装饰接口,增加了状态属性和刷新状态的动作
public interface IDecorator : IText
{
    IState State { get; set; }
    void Refresh(IState newState) where T : IDecorator;
}

public abstract class DecoratorBase : IDecorator
{
    protected IText target;
    public DecoratorBase(IText target)
    {
        this.target = target;
    }
    public abstract string Content { get; }
    public IState State { get; set; }

    //更新状态
    public virtual void Refresh(IState newState) where T : IDecorator
    {
        if (this.GetType() == typeof(T))
        {
            if (newState == null)
            {
                State = null;
            }
            if (State != null && !State.Equals(newState))
            {
                State = newState;
            }
        }
        if (target != null && typeof(IDecorator).IsAssignableFrom(target.GetType()))
        {
            ((IDecorator)target).Refresh(newState);
        }
    }

}    

public class BoldDecorator : DecoratorBase
{
    public BoldDecorator(IText target) : base(target)
    {
        base.State = new BoldState();
    }

    public override string Content
    {
        get
        {
            if (((BoldState)State).IsBold)
            {
                return $"{base.target.Content}";
            }
            else
            {
                return base.target.Content;
            }
        }
    }
}

public class ColorDecorator : DecoratorBase
{
    public ColorDecorator(IText target) : base(target)
    {
        base.State = new ColorState();
    }

    public override string Content
    {
        get
        {
            if (State != null)
            {
                string colorName = (((ColorState)State).Color).Name;
                return $"{base.target.Content}";
            }
            else
            {
                return base.target.Content;
            }      
        }
    }
}
 
static void Main(string[] args)
{
    IText text = new TextObject();
    //默认不加粗、黑色字体
    text = new BoldDecorator(text);
    text = new ColorDecorator(text);
    Console.WriteLine(text.Content);  //< Black > hello 

    //修改为加粗、红色字体
    ColorState colorState = new ColorState();
    colorState.Color = Color.Red;
    BoldState boldState = new BoldState();
    boldState.IsBold = true;
    IDecorator root = (IDecorator)text;
    root.Refresh(colorState);
    root.Refresh(boldState);
    Console.WriteLine(text.Content); //< Red >< b > hello 

    //取消颜色设置
    colorState = null;
    root.Refresh(colorState);
    Console.WriteLine(text.Content); //< b > hello 
}
 

 

标签:target,newState,模式,public,Content,new,设计模式,装饰
来源: https://www.cnblogs.com/cdaniu/p/16403799.html