C#设计模式---装饰模式(Decorator Pattern)
一、目的
动态的为一个现有对象添加额外的职能。
二、定义
装饰者模式以对客户透明的方式动态地给一个对象添加额外的功能。
三、场景
假设我们从商店购买一部新手机,买回来之后,我们需要对新手机进行贴膜和包壳操作,以下我们将采用装饰模式来模拟这一场景。
四、实现

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 //装饰者模式:扩展原来初始对象的功能 6 namespace DesignMode_Deco 7 { 8 /// <summary> 9 /// 需要被装饰的抽象对象 10 /// </summary> 11 public abstract class Phone 12 { 13 public abstract void Print(); 14 public string State { get; set; } 15 } 16 17 public class ApplePhone : Phone 18 { 19 public ApplePhone() 20 { 21 State = "原始苹果手机"; 22 } 23 public override void Print() 24 { 25 Console.WriteLine(State); 26 } 27 28 } 29 /// <summary> 30 /// 装饰抽象类,要让装饰完全取代抽象组件,所以必须继承自Phone 31 /// </summary> 32 public abstract class Decorator : Phone 33 { 34 public Phone _phone; 35 public Decorator(Phone phone) 36 { 37 this._phone = phone; 38 } 39 40 public override void Print() 41 { 42 43 if (_phone != null) 44 { 45 _phone.Print(); 46 } 47 } 48 49 } 50 51 public class Sticker : Decorator 52 { 53 public Sticker(Phone phone):base(phone) 54 { 55 State = phone.State; 56 } 57 58 public override void Print() 59 { 60 AddSticker(); 61 Console.WriteLine(State); 62 } 63 /// <summary> 64 /// 新的行为方法 65 /// </summary> 66 public void AddSticker() 67 { 68 State = State + " + 贴膜"; 69 70 } 71 } 72 73 public class Accessory : Decorator 74 { 75 public Accessory(Phone phone) 76 : base(phone) 77 { 78 State = phone.State; 79 } 80 81 public override void Print() 82 { 83 AddAccessory(); 84 Console.WriteLine(State); 85 } 86 87 public void AddAccessory() 88 { 89 State = State + " + 包壳"; 90 } 91 } 92 class Program 93 { 94 static void Main(string[] args) 95 { 96 Phone myPhone = new ApplePhone(); 97 Decorator myStickerDecorator = new Sticker(myPhone); 98 myStickerDecorator.Print(); 99 Console.WriteLine("****************************"); 100 101 Decorator myAccessoryDecorator = new Accessory(myPhone); 102 myAccessoryDecorator.Print(); 103 104 Console.WriteLine("****************************"); 105 106 Decorator myAccessoryWithStickerDecorator = new Accessory(myStickerDecorator); 107 myAccessoryWithStickerDecorator.Print(); 108 Console.WriteLine("****************************"); 109 110 Decorator myAccessoryWithStickerDecorator2 = new Accessory(myAccessoryWithStickerDecorator); 111 myAccessoryWithStickerDecorator2.Print(); 112 } 113 } 114 }
运行结果如下:
五、类图
六、描述
装饰模式中,主要包括抽象产品、具体产品、抽象装饰者和具体装饰者。为了能让装饰者完全替代产品,抽象装饰者需要和具体产品继承同一个抽象的产品接口。
抽象构件(Phone)角色:给出一个抽象接口,以规范准备接受附加责任的对象。
具体构件(ApplePhone)角色:定义一个将要接收附加责任的类。
装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰(Sticker和Accessories)角色:负责给构件对象 ”贴上“附加的责任。