外观模式给子系统的一组接口提供了一致的访问界面,提供了一个高层访问接口,降低了访问复杂系统内部子系统的复杂度。在客户端和负责系统间增加一层,将调用顺序、依赖关系等处理好,比如说Java的三层开发模式。
外观模式的优点是减少系统相互依赖,提高灵活性、安全性;缺点是不符合开闭原则,如果要改东西很麻,继承重写都不合适。
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw method.");
}
}
public class Circle implements Shape {
@Override
public void draw(){
System.out.println("Inside Circle::draw method.");
}
}
public class Square implements Shape {
@Override
public void draw(){
System.out.println("Inside Square::draw method.");
}
}
public class UnknownShape implements Shape {
@Override
public void draw(){
System.out.println("Inside UnknownShape::draw method.");
}
}
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape unknownShape;
private Shape square;
ShapeMaker(){
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
unknownShape = new UnknownShape();
}
void drawCircle(){
circle.draw();
}
void drawRectangle(){
rectangle.draw();
}
void drawSquare(){
square.draw();
}
void drawUnknownShape(){
unknownShape.draw();
}
}
public class FacadeInstance {
public static void main(String[] args) {
ShapeMaker maker = new ShapeMaker();
maker.drawCircle();
maker.drawRectangle();
maker.drawSquare();
maker.drawUnknownShape();
}
}