文章目录
介绍
描述
外观模式设计模式属于结构型模式,是隐藏系统的复杂性,并向客户端提供了一个可以访问系统的接口,涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统方法的委托调用。当一个系统子系统越来越多,访问也将越来越复杂,当系统内部发生改变,客户端也要改变,违背了 “开闭原则” 和 “迪米特法则” ,所以提供一个统一的接口,可以降低系统的耦合度。
特点
优点:对客户而言操作起来更加容易,降低了复杂性。
缺点:新的子类增加,就可能导致修改外观类。
实现原理
在客户端和复杂系统之间再加一层外观类,使得客户端不与系统耦合,外观类与系统耦合。
适用
-
为复杂的模块或子系统提供外界访问的模块,子系统相对独立。
外观模式
实现
简化去医院看病的挂号、门诊、开药、取药流程,转为提供接待人员统一处理(外观类)。
第一步:创建类Registration(挂号) 、Outpatient (门诊)、Drugstore (药方)。
// 挂号
public class Registration {
private static Registration instance = new Registration();
public static Registration getInstance() {
return instance;
}
public void handle(){
System.out.println("挂号 中...");
}
}
// 诊断
public class Outpatient {
private static Outpatient instance = new Outpatient();
public static Outpatient getInstance() {
return instance;
}
public void handle(){
System.out.println("诊断 中...");
}
}
// 药方
public class Drugstore {
private static Drugstore instance = new Drugstore();
public static Drugstore getInstance() {
return instance;
}
public void on(){
System.out.println("开药 中...");
}
public void off(){
System.out.println("取药 中...");
}
}
第二步:创建外观类Reception ,完成子系统调用流程。
// 外观类(接待人员)
public class Reception {
private Registration registration;
private Outpatient outpatient;
private Drugstore drugstore;
public Reception() {
super();
registration = Registration.getInstance();
outpatient = Outpatient.getInstance();
drugstore = Drugstore.getInstance();
}
public void open(){
// 处理流程
registration.handle();
outpatient.handle();
drugstore.on();
drugstore.off();
end();
}
private void end(){
System.out.println("流程 结束...");
}
}
第三步:测试。
public class Test {
public static void main(String[] args) {
Reception reception = new Reception();
reception.open();
/*
挂号 中...
诊断 中...
开药 中...
取药 中...
流程 结束...
*/
}
}