1.简介
外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
2.小例子
分别有画图类Rectangle Square Circle,如果在系统中直接使用,就需要分别实例化这3个对象,然后再对应调用画图方法。如果用外观模式,想画什么图,就直接调用方法,简化了系统调用。
3.代码如下
public interface Shape {
void draw();
}
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");
}
}
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
this.circle = new Circle();
this.rectangle = new Rectangle();
this.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();
}
}
网友评论