简介
基本内容
外观模式(Facade),也叫 “ 过程模式:外观模式为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
外观模式通过定义一个一致的接口,用以屏蔽内部子系统的细节,使得调用端只需跟这个接口发生调用,而无需关心这个子系统的内部细节。
外观模式(Facade),他隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。这种类型的设计模式属于结构性模式。为子系统中的一组接口提供了一个统一的访问接口,这个接口使得子系统更容易被访问或者使用。
外观模式类图如下:
外观模式主要包含角色:
外观类(Facade): 也叫门面角色,是外观模式的核心。为调用端提供统一的调用接口, 外观类知道哪些子系统负责处理请求,从而将调用端的请求代理给适当子系统对象。
调用者(Client): 外观接口的调用者。
子系统的集合:指模块或者子系统,处理 Facade对象指派的任务,他是功能的实际提供者。
示例
1.创建一个接口
依旧以图形类为例
public interface Shape {
void draw();
}
2.创建接口实现类
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
3.创建外观类(门面角色)
public class FacadeShape {
private Shape circle;
private Shape rectangle;
private Shape square;
public FacadeShape() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}
4.main方法验证
public class FacadeMain {
public static void main(String[] args) {
FacadeShape facadeShape = new FacadeShape();
facadeShape.drawCircle();
facadeShape.drawRectangle();
facadeShape.drawSquare();
}
}
分析
使用场景:
1、为复杂的模块或子系统提供外界访问的模块。
2、子系统相对独立。
3、预防低水平人员带来的风险。
优缺点:
优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。
缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。