一、定义
外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
解释:简单来说,客户端需要调用一个特别复杂的子系统中的多个接口,如果直接调用逻辑处理起来会非常复杂,而且不便于系统扩展。外观模式把这个复杂的子系统统一起来,提供几个高层接口,以备客户端进行调用。通俗来说是:子系统是一个黑匣子,提供若干个透明接口以备调用。
二、UML类图及基本代码
基本代码:
classPRogram
{staticvoidMain(string[] args)
{
Facade facade=newFacade();
facade.MethodA();
facade.MethodB();
Console.Read();
}
}classFacade
{
SubSystemOne systemOne;
SubSystemTwo systemTwo;
SubSystemThree systemThree;publicFacade()
{
systemOne=newSubSystemOne();
systemTwo=newSubSystemTwo();
systemThree=newSubSystemThree();
}publicvoidMethodA()
{
Console.WriteLine("\n方法组A()---");
systemOne.MethodOne();
systemThree.MethodThree();
}publicvoidMethodB()
{
Console.WriteLine("\n方法组B()---");
systemOne.MethodOne();
systemTwo.MethodTwo();
}
}classSubSystemOne
{publicvoidMethodOne()
{
Console.WriteLine("子系统方法一");
}
}classSubSystemTwo
{publicvoidMethodTwo()
{
Console.WriteLine("子系统方法二");
}
}classSubSystemThree
{publicvoidMethodThree()
{
Console.WriteLine("子系统方法三");
}
}
View Code
三、举例说明
一学校选课系统中有注册课程子系统和通知系统。正常情况下,需要一一调用注册课程系统和通知系统。如果使用外观模式,将注册课程系统和通知系统包装起来,为其提供一个统一接口以供学生调用。代码如下:
classProgram
{privatestaticRegistrationFacade facade =newRegistrationFacade();staticvoidMain(string[] args)
{if(facade.RegisterCourse("设计模式","studentA"))
{
Console.WriteLine("选课成功");
}else{
Console.WriteLine("选课失败");
}
Console.Read();
}
}publicclassRegistrationFacade
{privateRegisterCourse registerCourse;privateNotifyStudent notifyStudent;publicRegistrationFacade()
{
registerCourse=newRegisterCourse();
notifyStudent=newNotifyStudent();
}publicboolRegisterCourse(stringcourseName,stringstudentName)
{if(!registerCourse.CheckAvailable(courseName))
{returnfalse;
}returnnotifyStudent.Notify(studentName);
}
}publicclassRegisterCourse
{publicboolCheckAvailable(stringcourseName)
{
Console.WriteLine("正在验证课程{0}是否人数已满", courseName);returntrue;
}
}publicclassNotifyStudent
{publicboolNotify(stringstudentName)
{
Console.WriteLine("正在向{0}发出通知", studentName);returntrue;
}
}
四、优缺点及使用场景
优点:
1)外观模式对客户端屏蔽了子系统组件,从而简化了接口,减少了客户端处理的对象数目并使子系统的使用更加简单。
2)外观模式实现了子系统与客户之间的松耦合关系,而子系统内部的功能组件是紧耦合的。松耦合使得子系统的组件变化不会影响到它的客户端。
缺点:
增加新的子系统可能需要修改外观类或客户端,违背了“开闭原则”。
使用场景:
1)为一个复杂的子系统提供一个简单的接口。
2)在层次化结构中,可以使用外观模式定义系统中每一层的入口。
3)子系统需要独立性。