一、模式简介
定义:对内整合多个子系统,对外提供统一接口。外部应用程序不用关心内部子系统具体的细节,大大降低了系统的复杂度和提高乐系统的可维护性。
场景:对分层结构系统构建时,使用外观模式定义子系统中每层的入口点可以简化子系统之间的依赖关系。当一个复杂系统的子系统很多时,外观模式可以为系统设计一个简单的接口供外界访问。当客户端与多个子系统之间存在很大的联系时,引入外观模式可将它们分离,从而提高子系统的独立性和可移植性。
- 角色结构:
- 外观(Facade)角色:为多个子系统对外提供一个共同的接口。
- 子系统(Sub System)角色:实现系统的部分功能,客户可以通过外观角色访问它。
- 客户(Client)角色:通过一个外观角色访问各个子系统的功能。
二、模式实现
public interface Shape { -> 抽象子系统
String shape();
}
public class Triangle implements Shape { -> 具体子系统
@Override
public String shape() {
return "三角形";
}
}
public class Rectangle implements Shape { -> 具体子系统
@Override
public String shape() {
return "长方形";
}
}
public class Facade { -> 外观类
private Shape triangle = new Triangle();
private Shape rectangle = new Rectangle();
public void triangle(){
System.out.println(this.triangle.shape());
}
public void rectangle(){
System.out.println(this.rectangle.shape());
}
}
Facade facade = new Facade();
facade.triangle();
facade.rectangle();