简介:外观模式(Facade Pattern)隐藏系统的复杂性,外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 外观模式又称为门面模式,它是一种对象结构型模式。
优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。
缺点:缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
设计概要:我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。下一步是定义一个外观类 ShapeMaker。
ShapeMaker 类使用实体类来代表用户对这些类的调用。FacadePatternDemo,我们的演示类使用 ShapeMaker 类来显示结果。
代码:
步骤 1
创建一个接口
public interface Shape {
void draw();
}
步骤 2
创建实现接口的实体类。
public class Circle implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("开始画圆!!!");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("开始画正方形!!!");
}
}
public class Square implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("开始画长方形!!!");
}
}
步骤 3
创建一个外观类。
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
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
使用该外观类画出各种类型的形状。
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
结果: