裝飾模式的核心:被裝飾對象(最原始),裝飾對象(帶有裝飾功能的被裝飾對象)。 假設有一個被裝飾對象叫“ConcreteComponent ”,兩個裝飾對象叫“ConcreteDecoratorA”、“ConcreteDecoratorB”。裝飾是錦上添花的事情,ConcreteComponent 被 ...
裝飾模式的核心:被裝飾對象(最原始),裝飾對象(帶有裝飾功能的被裝飾對象)。
假設有一個被裝飾對象叫“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類裝飾"); } } }View Code
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("工裝褲"); } } }