裝飾模式是在沒必要改變原類文件和使用繼承的狀況下,動態地擴展一個對象的功能。算法
public class Person { public string Name { get; set; } public Person() { } public Person(string name) { Name = name; } public virtual void Show() { Console.WriteLine(string.Format("裝扮的{0}", Name)); } } public class Finery : Person { protected Person component; public void Decorate(Person com) { component = com; } public override void Show() { if (component != null) { component.Show(); } } } public class Suit : Finery { public override void Show() { Console.WriteLine("穿西裝"); base.Show(); } } public class Tie : Finery { public override void Show() { Console.WriteLine("打領帶"); base.Show(); } } public class TShirts : Finery { public override void Show() { Console.WriteLine("大 T 恤"); base.Show(); } }
使用裝飾器的代碼: Person per = new Person("mao"); Console.WriteLine("第一種裝扮:"); TShirts ts = new TShirts(); Suit su = new Suit(); Tie tie = new Tie(); su.Decorate(per); tie.Decorate(su); ts.Decorate(tie); ts.Show();
普通代碼: Person perB = new Person("Mao"); Console.WriteLine("第二種裝扮:"); TShirts tsB = new TShirts(); Suit suB = new Suit(); Tie tieB = new Tie(); tsB.Show(); tieB.Show(); suB.Show(); perB.Show();
不只要看懂設計模式,還要知道在什麼場景下用。
好比裝飾模式和策略模式的區別,裝飾模式能夠勉強的理解爲按順序組裝多種策略在一塊兒,而策略模式就是選擇某一種策略並只暴露選擇策略的接口隱藏策略的實現算法。設計模式
第 2 個實現方式:ide
// 形狀 public abstract class Shape { public abstract void Draw(); } // 圓形 public class Circle : Shape { public override void Draw() { Console.WriteLine("Draw Circle"); } } // 方形 public class Rectangle : Shape { public override void Draw() { Console.WriteLine("Draw Rectangle"); } } // 形狀裝飾器 public class ShapeDecorator : Shape { protected Shape decoratedShape; public void SetDecorate(Shape sh) { decoratedShape = sh; } public override void Draw() { decoratedShape.Draw(); } } // 紅色的形狀裝飾器 public class RedShapeDecorator : ShapeDecorator { public override void Draw() { base.Draw(); Console.WriteLine("Draw Red"); } } // 黃色的形狀裝飾器 public class YellowShapeDecorator : ShapeDecorator { public override void Draw() { base.Draw(); Console.WriteLine("Draw Yellow"); } } //業務運用 Console.WriteLine(""); Console.WriteLine("第 1 種形狀:黃圓"); YellowShapeDecorator ys = new YellowShapeDecorator(); ys.SetDecorate(new Circle()); ys.Draw(); Console.WriteLine(""); Console.WriteLine("第 2 種形狀:紅方形"); RedShapeDecorator rs = new RedShapeDecorator(); rs.SetDecorate(new Rectangle()); rs.Draw(); Console.WriteLine(""); Console.WriteLine("第 3 種形狀:黃紅方形"); RedShapeDecorator rs2 = new RedShapeDecorator(); rs2.SetDecorate(new Rectangle()); YellowShapeDecorator ys2 = new YellowShapeDecorator(); ys2.SetDecorate(rs2); ys2.Draw();
輸出: 第 1 種形狀:黃圓 Draw Circle Draw Yellow 第 2 種形狀:紅方形 Draw Rectangle Draw Red 第 3 種形狀:黃紅方形 Draw Rectangle Draw Red Draw Yellow