实例
我们将创建一个Shape接口和实现Shape接口的具体类。下一步将定义外观类ShapeMaker。
ShapeMaker类使用具体的类将用户调用委派给这些类。我们的演示类FacadePatternDemo,将使用ShapeMaker类来显示结果。
第1步创建一个接口。Shape.java
public interface Shape {
void draw();
}
第2步 - 创建实现相同接口的具体类。Rectangle.java ,Square.java, Circle.java
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()");
}
}
第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()