本文共 2079 字,大约阅读时间需要 6 分钟。
1 、对象接口 Component.cs |
public abstract class Component { public abstract void Operation(); } |
2 、实现类 ConcreteComponent .cs 继承于 Component 接口 |
public class ConcreteComponent : Component { public override void Operation() { Console .WriteLine(" 开始执行具体的对象..." ); } } |
3 、装饰抽象类 Decorator.cs 继承于 Component 接口 |
public abstract class Decorator : Component { private Component m_Component; public void SetComponent(Component component) { this .m_Component = component; } public override void Operation() { if (m_Component != null ) { m_Component.Operation(); } } } |
4 、具体的装饰对象 ConcreteDecoratorA.cs 继承于 Decorator 抽象类 |
public class ConcreteDecoratorA : Decorator { private string addedState; public override void Operation() { base .Operation(); addedState = " 进行了状态属性装饰。" ; Console .WriteLine(addedState); } } |
给对象接口 Component 添加了状态属性 addedState |
5 、具体的装饰对象 ConcreteDecoratorB.cs 继承于 Decorator 抽象类 |
public class ConcreteDecoratorB : Decorator { public override void Operation() { base .Operation(); AddedBehavior(); } private void AddedBehavior() { Console .WriteLine(" 进行了操作行为装饰。" ); } } |
给对象接口 Component 添加了操作行为 AddedBehavior() |
5 、客户端代码 |
static void Main (string [] args) { ConcreteComponent cc = new ConcreteComponent (); ConcreteDecoratorA cda = new ConcreteDecoratorA (); ConcreteDecoratorB cdb = new ConcreteDecoratorB (); cda.SetComponent(cc); cdb.SetComponent(cda); cdb.Operation(); Console .Read(); } |
给对象接口 Component 添加了操作行为 AddedBehavior() |