外观模式隐藏了系统的复杂性,并提供了到客户端的接口,客户端可以使用该接口访问系统。这种设计模式属于结构模式,因为该模式向现有系统添加了接口以隐藏其复杂性。
无涯教程将创建一个 Shape 接口和实现 Shape 接口的具体类,下一步将定义外观类 ShapeMaker 。
ShapeMaker 类使用具体的类将用户调用委派给这些类,演示类 FacadePatternDemo 将使用 ShapeMaker 类显示结果。
第1步 - 创建一个Shape接口。
Shape.java
public interface Shape { void draw(); }
第2步 - 创建实现Shape接口的具体类。
Rectangle.java
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } }
Square.java
public class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } }
Circle.java
public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } }
第3步 - 创建一个外观类。
ShapeMaker.java
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步 - 使用立面绘制各种类型的形状。
FacadePatternDemo.java
public class FacadePatternDemo { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } }
第5步 - 验证输出。
Circle::draw() Rectangle::draw() Square::draw()
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)