大话设计-装饰模式
装饰模式的核心:被装饰对象(最原始),装饰对象(带有装饰功能的被装饰对象)。
假设有一个被装饰对象叫“ConcreteComponent ”,两个装饰对象叫“ConcreteDecoratorA”、“ConcreteDecoratorB”。装饰是锦上添花的事情,ConcreteComponent 被装饰之前已经最好了最基本的工作,ConcreteDecoratorA和ConcreteDecoratorB只是在这个基本工作里额外加了些工作。
装饰是无序的,可以ConcreteDecoratorA先装饰ConcreteComponent,然后ConcreteDecoratorB装饰ConcreteDecoratorA。也可以ConcreteDecoratorB先装饰ConcreteComponent,然后ConcreteDecoratorA装饰ConcreteDecoratorB。
被装饰对象和装饰类是否需要抽象跟这里的装饰模式无关。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { ConcreteComponent concreteComponent = new ConcreteComponent(); ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(); ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(); concreteDecoratorA.SetComponent(concreteComponent); concreteDecoratorB.SetComponent(concreteDecoratorA); concreteDecoratorB.Operation(); } } 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 addState; public override void Operation() { base.Operation(); addState = "A addState"; Console.WriteLine("A类装饰"); } } class ConcreteDecoratorB : Decorator { private string addState; public override void Operation() { base.Operation(); addState = "B addState"; Console.WriteLine("B类装饰"); } } }
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { Person person = new Person("白石"); TShirts shirts = new TShirts(); Overalls overalls = new Overalls(); shirts.Decorate(person); overalls.Decorate(shirts); } } class Person { public Person() { } private string name; public Person (string name) { this.name = name; } public virtual void Show() { // 什么装饰都没有的基本展示。 Console.WriteLine($"{name} 一个人的基本show"); } } abstract class Finery : Person { protected Person component; public void Decorate(Person person) { this.component = person; } public override void Show() { if (component != null) { component.Show(); } } } class TShirts : Finery { public override void Show() { base.Show(); Console.WriteLine("穿T恤"); } } class Overalls : Finery { public override void Show() { base.Show(); Console.WriteLine("工装裤"); } } }
量变会引起质变。