描述
外观模式很好理解,就是一个复杂的类,把其中所有成员都设置为私有,同时为每个成员写一个公有的操作函数,很经典的就是我们平时写model时把成员变量定义为私有,同时为每个成员变量写get和set方法。
使用场景:当访问者不需要知道内部复杂联系,只需要调用内部功能时时候,常常定义系统入口。
实例
上边描述的已经够清楚了,下边给个实例:
class ShapeFacade { interface Shape { void draw(); } class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } } class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } } class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } } private Shape circle = new Circle(); private Shape rectangle = new Rectangle(); private Shape square = new Square(); public ShapeFacade() { } public void drawCircle() { circle.draw(); } public void drawRectangle() { rectangle.draw(); } public void drawSquare() { square.draw(); } } public class Main { public static void main(String[] args) { ShapeFacade shapeFacade = new ShapeFacade(); shapeFacade.drawCircle(); shapeFacade.drawRectangle(); shapeFacade.drawSquare(); } }
运行结果:
代码来源:特别感谢 w3school设计模式之外观模式