以穿衣为例:
Component类:可以通过ConcreteComponent类动态添加职责
namespace Dacoration_Pattern.Class { abstract class Component { public abstract void Show(); } }
ConcreteComponent类:定义了具体的职责
namespace Dacoration_Pattern.Class { class ConCreteComponent:Component { private string name; public ConCreteComponent(string name) { this.name = name; } public override void Show() { Console.WriteLine("装扮的{0}",name); } } }
Decorator类:
namespace Dacoration_Pattern.Class { class Decorator:Component { protected Component person; public void Decorate(Component person) { this.person = person; } public override void Show() { if (person != null) { person.Show(); } } } }
ConcreteDecoratorA类:
namespace Dacoration_Pattern.Class { class ConCreteDecoratorA:Decorator { public override void Show() { Console.WriteLine("大T恤"); base.Show(); } } }
ConcreteDecoratorB类:
namespace Dacoration_Pattern.Class { class ConcretrDecoratorB:Decorator { public override void Show() { Console.WriteLine("跨裤"); base.Show(); } } }
ConcreteDecoratorC类:
namespace Dacoration_Pattern.Class { class ConcreteDecoratorC:Decorator { public override void Show() { Console.WriteLine("皮鞋"); base.Show(); } } }
客户端代码(TestMain)类:
namespace Dacoration_Pattern { class TestMain { static void Main(string[] args) { ConCreteComponent person = new ConCreteComponent("张三"); Console.WriteLine("第一种装扮:"); ConCreteDecoratorA ConA = new ConCreteDecoratorA(); ConcretrDecoratorB ConB = new ConcretrDecoratorB(); ConcreteDecoratorC ConC = new ConcreteDecoratorC(); ConA.Decorate(person); ConB.Decorate(ConA); ConB.Show(); ConCreteComponent person1 = new ConCreteComponent("李四"); Console.WriteLine("第二种装扮:"); ConB.Decorate(person1); ConC.Decorate(ConB); ConC.Show(); Console.ReadLine(); } } }
装饰模式结束!
要么忍,要么狠,要么滚!