门面模式通过统一的抽象接口访问具体实现,让使用者可以无痛更换具体实现,在目前的日志系统中广泛使用。

1 演示代码

创建统一抽象接口

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public interface Shape {
   void draw();
}

public class ShapeMaker {
   private Shape shape;
 
   public void drawShape(){
      shape.draw();
   }
   public void setShape(Shape shape) {
       this.shape = shape;
   }
}

创建子类实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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()");
   }
}

创建测试

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class FacadePatternDemo {
    public static void main(String[] args) {
        ShapeMaker shapeMaker = new ShapeMaker();
        shapeMaker.setShape(new Rectangle());
        shapeMaker.drawShape();
        shapeMaker.setShape(new Square());
        shapeMaker.drawShape();
        shapeMaker.setShape(new Circle());
        shapeMaker.drawShape();
    }
}

参考资料

  1. 菜鸟教程: 外观模式