美文网首页工作生活
第十二章 外观模式(Facade Pattern)

第十二章 外观模式(Facade Pattern)

作者: 穹生变 | 来源:发表于2019-06-29 19:14 被阅读0次

1.简介

  • 为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加的容易使用。
  • 通过一个接口隐藏了后面的复杂逻辑,使用更加方便。
  • 外观模式是结构型模式

2.场景

1、为复杂的模块或子系统提供外界访问的模块。
2、子系统相对独立。
3、预防低水平人员带来的风险。

3.优缺点

优点:

1、减少系统相互依赖。
2、提高灵活性。
3、提高了安全性。

缺点:

不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

4. 图片模型

image.png

5. 代码实现

public interface Shape {
   void 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()");
   }
}
public class Circle implements Shape {
 
   @Override
   public void draw() {
      System.out.println("Circle::draw()");
   }
}
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();
   }
}
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();
 
      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();      
   }
}

输出结果:

Circle::draw()
Rectangle::draw()
Square::draw()

相关文章

网友评论

    本文标题:第十二章 外观模式(Facade Pattern)

    本文链接:https://www.haomeiwen.com/subject/wlmpcctx.html