1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace DesignPattern.StructuralPattern
8 {
9 #region 装饰器模式要点
10 //定义:以对客户透明的方式动态的为对象附加更多责任,装饰器相比子类可以更加灵活地增加新功能。
11 //1.使用组合而不是继承,更灵活,装饰器类都含有被装饰类的引用
12 //2.装饰器抽象类和被装饰类继承相同类或实现相同接口,为了使被装饰类和装饰类能够互换
13 //3.可以通过不同的装饰顺序,实现不同的行为的组合
14 //示例:Stream就使用了装饰器模式
15 //可以动态的为MemoryStream,FileStream,NetworkStream增加新的功能加密流,缓存流,压缩流等,都继承stream
16
17 /*
18 MemoryStream memoryStream = new MemoryStream(new byte[] {95,96,97,98,99});
19
20 // 扩展缓冲的功能
21 BufferedStream buffStream = new BufferedStream(memoryStream);
22
23 // 添加加密的功能
24 CryptoStream cryptoStream = new CryptoStream(memoryStream,new AesManaged().CreateEncryptor(),CryptoStreamMode.Write);
25
26 // 添加压缩功能
27 GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);
28 */
29
30 #endregion
31
32 //接口或者抽象类
33
34 public abstract class AbstractPrint
35 {
36 public abstract void Print();
37 }
38
39 //被装饰类
40 public class Printer : AbstractPrint
41 {
42 public override void Print()
43 {
44 Console.WriteLine("打印机开始打印");
45 }
46 }
47
48 public abstract class DecoratorPattern : AbstractPrint
49 {
50 Printer _printer = null;
51 public Printer MyPrinter
52 {
53 get { return _printer; }
54 set { _printer = value; }
55 }
56
57 public DecoratorPattern(Printer printer)
58 {
59 _printer = printer;
60 }
61
62
63
64 public override void Print()
65 {
66 if (_printer != null)
67 {
68 _printer.Print();
69 }
70 }
71 }
72
73 public class ConcreteDecoratorInk : DecoratorPattern
74 {
75 public ConcreteDecoratorInk(Printer printer) :base(printer)
76 {
77
78 }
79
80 //重写可以自己调整新增方法顺序
81 public override void Print()
82 {
83 DecoratorMethod();
84 base.Print();
85 }
86
87 public void DecoratorMethod()
88 {
89 Console.WriteLine("添加彩色油墨");
90 }
91 }
92
93
94 public class ConcreteDecoratorPapper : DecoratorPattern
95 {
96 public ConcreteDecoratorPapper(Printer printer) : base(printer)
97 {
98
99 }
100
101 //重写可以自己调整新增方法顺序
102 public override void Print()
103 {
104 base.Print();
105 DecoratorMethod();
106 }
107
108 public void DecoratorMethod()
109 {
110 Console.WriteLine("添加A4纸");
111 }
112 }
113 }