设计模式 - 9) 外观模式
发布日期:2021-05-13 19:47:08 浏览次数:17 分类:博客文章

本文共 1572 字,大约阅读时间需要 5 分钟。

比如开一台设备需要按顺序给显示器通电、亮灯、发出声音。

在使用外观模式前,客户端直接调用通电、亮灯、发出声音。
在这样的情况下,后续如果流程发生变化,比如不需要发出声音或声音需要在亮灯之前,就需要修改客户端的代码,如果客户端多处调用,就需要修改多处。

public class SubSystemOne{    public void MethodOne()    {        Console.WriteLine("子系统方法一");    }}public class SubSystemTwo{    public void MethodTwo()    {        Console.WriteLine("子系统方法二");    }}public class SubSystemThree{    public void MethodThree()    {        Console.WriteLine("子系统方法三");    }}// 业务调用SubSystemOne one = new SubSystemOne();one.MethodOne();            SubSystemTwo two = new SubSystemTwo();two.MethodTwo();

使用外观模式以后,业务系统在启动的时候只需要按下开关,由开关去触发通电、亮灯、发出声音的操作。业务端的代码只需要按下开关。后续如果流程发生变化,只需要修改 Facade 类。

public class SubSystemOne{    public void MethodOne()    {        Console.WriteLine("子系统方法一");    }}public class SubSystemTwo{    public void MethodTwo()    {        Console.WriteLine("子系统方法二");    }}public class SubSystemThree{    public void MethodThree()    {        Console.WriteLine("子系统方法三");    }}public class Facade{    SubSystemOne one;    SubSystemTwo two;    SubSystemThree three;        public Facade()    {        one = new SubSystemOne();        two = new SubSystemTwo();        three = new SubSystemThree();    }    public void MethodA()    {        Console.WriteLine("\n方法组A:");        one.MethodOne();        two.MethodTwo();                }    public void MethodB()    {        Console.WriteLine("\n方法组B:");        two.MethodTwo();        three.MethodThree();    }}// 业务调用Facade f = new Facade();f.MethodA();            f.MethodB();

可用于如果 新系统 需要调用 遗留代码 中逻辑比较复杂的代码时,可使用外观模式,由 Facede 类去封装复杂的逻辑,并提供简单的接口给新系统使用。

上一篇:设计模式 - 10)建造者模式
下一篇:设计模式 - 8) 模板模式

发表评论

最新留言

很好
[***.229.124.182]2025年04月19日 05时33分16秒