1、个人理解:将主类中的不定个数的、无序的额外处理划分为多个类,在客户端的时候能够对这些额外处理随意与主体类进行组织。
看一段代码(根据别人的Java代码改的):卖饼,手抓饼和肉夹馍两种,可以添加的辅料有煎蛋、肉松等。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 装饰者模式2{ class Program { static void Main(string[] args) { Test test = new Test(); test.test(); } } public abstract class Pancake { public string desc = "我不是一个具体的饼"; public double price = 0; public string GetDesc() { return desc; } } ////// 手抓饼 /// public class TornCake : Pancake { public TornCake() { desc = "手抓饼"; price = 4; } } ////// 肉夹馍 /// public class Roujiamo : Pancake { public Roujiamo() { desc = "肉夹馍"; price = 6; } } ////// 作料 /// public abstract class Condiment : Pancake { protected Pancake pancake; public abstract string getDesc(); public abstract void AddCondiment(Pancake pancake); } ////// 煎蛋 /// public class FiredEgg : Condiment { public FiredEgg() { price = 1; desc = "煎蛋"; } public override string getDesc() { return pancake.GetDesc() + ", 加煎蛋"; } public override void AddCondiment(Pancake pancake) { this.pancake = pancake; pancake.price += price; pancake.desc += ", 加" + desc; } } ////// 黄瓜 /// public class Cucumber : Condiment { public Cucumber() { price = 2; desc = "黄瓜"; } public override string getDesc() { return pancake.GetDesc() + ", 加" + desc; ; } public override void AddCondiment(Pancake pancake) { this.pancake = pancake; pancake.price += 2; pancake.desc += ", 加黄瓜"; } } class Test { public void test() { Pancake pancake = new TornCake(); //手抓饼基础价 Console.WriteLine("描述:{0}, 基础价格:{1}", pancake.GetDesc(), pancake.price); Pancake roujiamo = new Roujiamo(); //肉夹馍基础价 Console.WriteLine("描述:{0}, 基础价格:{1}", roujiamo.GetDesc(), roujiamo.price); FiredEgg fireEgg = new FiredEgg(); Cucumber Cucumber = new Cucumber(); fireEgg.AddCondiment(roujiamo); Cucumber.AddCondiment(roujiamo); Console.WriteLine("描述:{0}, 价格:{1}", roujiamo.GetDesc(), roujiamo.price); Console.ReadLine(); } }}