装饰模式定义:动态给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活
Component是定义了一个对象接口,可以给这些对象动态添加职责。
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责
Decorator装饰抽象类,继承了Component从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorater的存在。至于ConcreteDecorator,起到给Component添加职责的功能
装饰模式是为已有功能动态添加功能的方式,当系统需要新功能时,向旧的类添加代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。装饰模式提供了一个非常好的解决方案,把每个要装饰的功能放在单独的类中,并让这个类包装它所需要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行根据需要有选择的、按顺序使用装饰功能包装对象了
优点:把类的装饰功能从类中移除,可以简化原有的类。有效把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑
using System; using System.Collections.Generic; using System.Text; namespace 装饰模式 { class Program { static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); Console.Read(); } } abstract class Component { public abstract void Operation(); } class ConcreteComponent : Component { public override void Operation() { Console.WriteLine("具体对象的操作"); } } abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation() { if (component != null) { component.Operation(); } } } class ConcreteDecoratorA : Decorator { private string addedState; public override void Operation() { base.Operation(); addedState = "New State"; Console.WriteLine("具体装饰对象A的操作"); } } class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("具体装饰对象B的操作"); } private void AddedBehavior() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 装饰模式 { class Person { public Person() { } private string name; public Person(string name) { this.name = name; } public virtual void Show() { Console.WriteLine("装扮的{0}", name); } } class Finery:Person { protected Person component; public void Decorate(Person component) { this.component = component; } public override void Show() { if (component != null) component.Show(); } } class TShirts:Finery { public override void Show() { Console.Write("Tshirts "); base.Show(); } } class BigTrouser:Finery { public override void Show() { Console.Write("BigTrouser "); base.Show(); } } class Sneaks : Finery { public override void Show() { Console.Write("Sneaks "); base.Show(); } } class Program { static void Main(string[] args) { Person zyj = new Person("zyj"); Sneaks snk = new Sneaks(); BigTrouser bt = new BigTrouser(); TShirts ts = new TShirts(); snk.Decorate(zyj); bt.Decorate(snk); ts.Decorate(bt); ts.Show(); Console.Read(); } } }