慢慢说设计模式:外观模式

261 阅读1分钟

小Q:什么是设计模式

慢慢:设计模式是系统服务设计中针对常见场景的一种解决方案,可以解决功能逻辑开发中遇到的共性问题。设计模式并不局限最终的实现方案,而是在这种概念模式下,解决系统设计中的代码逻辑问题。

小Q:什么是外观模式

慢慢:外观模式隐藏系统的复杂性,并向客户端提供了一个客户端可以访问的接口。这种设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。

小Q:懂了,赶快上代码吧。

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 ShapeMaker {
    private String rectangle;
    private Shape square;
    
    public ShapeMaker() {
      rectangle = new Rectangle();
      square = new Square();
   }
 
   public void drawRectangle(){
      rectangle.draw();
   }
   public void drawSquare(){
      square.draw();
   }
}

使用该外观类画出各种形状

public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();
 
      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();      
   }
}

小Q:外观模式和适配器模式有什么区别呢?

慢慢:外观模式是对复杂对象的封装,对外暴露一个简单的接口。适配器是对一类相似功能的对象进行封装,对外暴露统一的接口。