【设计模式】外观模式——“知道有它就行了,内容不要你懂。”
【前言】
最近在进行机房收费系统的重构,三层架构中加了两个设计模式——外观和抽象工厂。所以,又拿出了设计模式的书再复习一下。 再看外观模式就像一个主机的外壳——子系统内部有哪些接口你不需要知道,你客户端只要知道我外观层提供给的接口就好了。用外观模式, 就像米老师讲快速阅读时说的:“知道有它就行了,内容不要你懂。”
【UML图】
【demo实现】
外观类:
复制代码
1
2<span style="font-size:24px;">using System; namespace System </span>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48<span style="font-size:24px;">{ public class facade { SubSystemOne one; SubSystemTwo two; SubsystemThree three; SubSystemFour four; public facade() { one = new SubSystemOne(); two = new SubSystemTwo(); three = new SubsystemThree(); four = new SubSystemFour(); } ~facade() { } public virtual void Dispose(){ } public void MethodA() { Console.WriteLine("n 方法组A()————"); one.MethodOne(); two .MethodTwo (); four.MethodFour(); } public void MethodB() { Console.WriteLine("n 方法组B()————"); two.MethodTwo(); three.Methodthree(); } }//end facade }//end namespace System</span>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23<span style="font-size:24px;">namespace System { public class SubSystemOne { public SubSystemOne(){ } ~SubSystemOne(){ } public virtual void Dispose(){ } public void MethodOne(){ Console.WriteLine("子系统方法一"); } }//end SubSystemOne }//end namespace System</span>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23<span style="font-size:24px;">namespace System { public class SubSystemTwo { public SubSystemTwo(){ } ~SubSystemTwo(){ } public virtual void Dispose(){ } public void MethodTwo() { Console.WriteLine("子系统方法二"); } }//end SubSystemTwo }//end namespace System</span>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<span style="font-size:24px;">namespace System { public class SubsystemThree { public SubsystemThree(){ } ~SubsystemThree(){ } public virtual void Dispose(){ } public void Methodthree(){ Console.WriteLine("子系统方法三"); } }//end SubsystemThree }//end namespace System</span>
复制代码
客户端代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27<span style="font-size:24px;">namespace System { public class SubSystemFour { public SubSystemFour(){ } ~SubSystemFour(){ } public virtual void Dispose() { } public void MethodFour() { Console .WriteLine("子系统方法四"); } } }</span>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<span style="font-size:24px;">namespace ConsoleApplication4 { class Program { static void Main(string[] args) { facade facade = new facade(); facade.MethodA(); facade.MethodB(); Console.Read(); } } } </span>
【适用情况】
1.三层架构中
2.子系统因为不断重构演化而变得越来越复杂,用facade减少依赖
3.维护一个遗留的大型系统中,用facade来与新系统交互。
【优点】
(1)实现了子系统与客户端之间的松耦合关系。
(2)客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起来更加容易。
【总结】
设计模式的核心就是解耦, 就是一些解耦合的方法。
最后
以上就是故意电脑最近收集整理的关于【设计模式】外观模式——“知道有它就行了,内容不要你懂。”的全部内容,更多相关【设计模式】外观模式——“知道有它就行了内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复