Facade Pattern, 即外观模式,用于隐藏复杂的系统内部逻辑,提供简洁的接口给客户端调用,属于结构类的设计模式。我会将其名字理解为,门户模式。
下面是 Facade Pattern 的一个简单案例。
Shape 定义一个接口,Circle, rectangle, Square 分别实现 Shape 接口,代表系统内部的一个功能。ShapeMaker 作为一个对外类,提供简洁的接口给外部调用。
代码实现:
Shape 接口
public interface Shape { public void draw(); }
Circle, Rectangle, Square 具体类实现 Shape 接口
public class Circle implements Shape { @Override public void draw() { System.out.println(" circle 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 "); } }
ShapeMaker,提供简洁的接口给外部客户端调用
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(); } }
演示 Facade Pattern
public class FacadePatternDemo { public static void main(){ ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } }
参考资料
Design Patterns - Facade Pattern, TutorialsPoint
时间: 2024-10-19 09:39:11