外观(Facade)模式,又叫做门面模式,它为一组接口提供了一个一致界面。外观模式定义了一个高层接口,这个接口使这一组接口更加容易使用

    日常使用Spring开发中,在高层模块需要使用多个子系统,我们都会创建一个新的类封装这些子系统,对外提供,这其实也是外观模式的一种体现。

    外观模式是“迪米特法则”的典型应用,有如下优点:

    1. 降低子系统和客户端的耦合度
    2. 简化了使用过程

    缺点:

    1. 增加新的子系统就需要修改代码,违背了开闭原则

    结构实现:

    外观模式结构比较简单,主要是定义了一个高层接口,包含了对各个子系统的引用

    1. 外观角色:高层接口,对外提供服务,内部引用多个子子系统
    2. 子系统:实现整个系统的部分功能,客户端可以通过外观角色访问
    3. 客户端:调用方,通过外观访问不同的子角色

    示例:
    现在有一些积木玩具,这些积木都被放在一个盒子里面,现在我们需要从盒子里面取出方形的积木。

    1. public static void main(String[] args) {
    2. Facade facade = new FacadeImpl();
    3. System.out.println(facade.getSquare());//方形积木
    4. }
    5. // 外观--提供操作
    6. interface Facade{
    7. // 获取方形
    8. String getSquare();
    9. // 获取圆形
    10. String getCircle();
    11. }
    12. // 实现外观操作
    13. static class FacadeImpl implements Facade{
    14. Square square = new Square();
    15. Circle circle = new Circle();
    16. @Override
    17. public String getSquare() {
    18. return square.toString();
    19. }
    20. @Override
    21. public String getCircle() {
    22. return circle.toString();
    23. }
    24. }
    25. // 子系统1
    26. static class Square{
    27. @Override
    28. public String toString() {
    29. return "方形积木";
    30. }
    31. }
    32. // 子系统2
    33. static class Circle{
    34. @Override
    35. public String toString() {
    36. return "圆形积木";
    37. }
    38. }