设计模式设计模式重温设计模式 --- 装饰器模式
Fantasy-ke引言
装饰器模式是一种结构型设计模式,它允许在不改变原始对象的情况下,通过将其包装在一个装饰器对象中,来动态地添加额外的功能。
装饰器模式的核心思想是,将一个对象放在另一个对象的外面,以给原始对象添加新的行为。这个“另一个对象”就是装饰器(Decorator),它持有一个原始对象(Component)的引用,并实现与原始对象相同的接口。装饰器可以通过调用原始对象的方法,来执行自己的行为。这种方式可以动态地添加、删除或替换对象的行为,而不需要修改原始对象的代码。
基本类接口
定义一个基本对象接口或抽象类,称为Component,它定义了一些基本操作:
1 2 3 4 5
| public interface IComponent { void Operation(); }
|
基本类实现
定义一个实现IComponent接口的具体类:
1 2 3 4 5 6 7 8
| public class ConcreteComponent : IComponent { public void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } }
|
装饰器抽象
定义一个装饰器抽象类或接口,称为Decorator,它也实现了Component接口,并在其中添加了一些新的操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public abstract class Decorator : IComponent { private IComponent component;
public Decorator(IComponent component) { this.component = component; }
public virtual void Operation() { component.Operation(); } }
|
装饰器实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class ConcreteDecoratorA : Decorator { public ConcreteDecoratorA(IComponent component) : base(component) { }
public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorA.Operation()"); } }
public class ConcreteDecoratorB : Decorator { public ConcreteDecoratorB(IComponent component) : base(component) { }
public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } }
|
接着,我们可以创建并使用一个具有特定功能对象:
1 2 3 4 5 6 7
| new ConcreteComponent();
IComponent decoratorA = new ConcreteDecoratorA(component);
IComponent decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB.Operation();
|
输出如下: