1、定义设计模式
外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。ide
解释:简单来讲,客户端须要调用一个特别复杂的子系统中的多个接口,若是直接调用逻辑处理起来会很是复杂,并且不便于系统扩展。外观模式把这个复杂的子系通通一块儿来,提供几个高层接口,以备客户端进行调用。通俗来讲是:子系统是一个黑匣子,提供若干个透明接口以备调用。spa
2、UML类图及基本代码设计
基本代码:code
class Program { static void Main(string[] args) { Facade facade = new Facade(); facade.MethodA(); facade.MethodB(); Console.Read(); } } class Facade { SubSystemOne systemOne; SubSystemTwo systemTwo; SubSystemThree systemThree; public Facade() { systemOne = new SubSystemOne(); systemTwo = new SubSystemTwo(); systemThree = new SubSystemThree(); } public void MethodA() { Console.WriteLine("\n方法组A()---"); systemOne.MethodOne(); systemThree.MethodThree(); } public void MethodB() { Console.WriteLine("\n方法组B()---"); systemOne.MethodOne(); systemTwo.MethodTwo(); } } class SubSystemOne { public void MethodOne() { Console.WriteLine("子系统方法一"); } } class SubSystemTwo { public void MethodTwo() { Console.WriteLine("子系统方法二"); } } class SubSystemThree { public void MethodThree() { Console.WriteLine("子系统方法三"); } }
3、举例说明对象
一学校选课系统中有注册课程子系统和通知系统。正常状况下,须要一一调用注册课程系统和通知系统。若是使用外观模式,将注册课程系统和通知系统包装起来,为其提供一个统一接口以供学生调用。代码以下:blog
class Program { private static RegistrationFacade facade = new RegistrationFacade(); static void Main(string[] args) { if (facade.RegisterCourse("设计模式", "studentA")) { Console.WriteLine("选课成功"); } else { Console.WriteLine("选课失败"); } Console.Read(); } } public class RegistrationFacade { private RegisterCourse registerCourse; private NotifyStudent notifyStudent; public RegistrationFacade() { registerCourse = new RegisterCourse(); notifyStudent = new NotifyStudent(); } public bool RegisterCourse(string courseName, string studentName) { if (!registerCourse.CheckAvailable(courseName)) { return false; } return notifyStudent.Notify(studentName); } } public class RegisterCourse { public bool CheckAvailable(string courseName) { Console.WriteLine("正在验证课程{0}是否人数已满", courseName); return true; } } public class NotifyStudent { public bool Notify(string studentName) { Console.WriteLine("正在向{0}发出通知", studentName); return true; } }
4、优缺点及使用场景接口
优势:string
1)外观模式对客户端屏蔽了子系统组件,从而简化了接口,减小了客户端处理的对象数目并使子系统的使用更加简单。it
2)外观模式实现了子系统与客户之间的松耦合关系,而子系统内部的功能组件是紧耦合的。松耦合使得子系统的组件变化不会影响到它的客户端。
缺点:
增长新的子系统可能须要修改外观类或客户端,违背了“开闭原则”。
使用场景:
1)为一个复杂的子系统提供一个简单的接口。
2)在层次化结构中,可使用外观模式定义系统中每一层的入口。
3)子系统须要独立性。