设计模式之外观(Facade)方式(笔记)

设计模式之外观(Facade)模式(笔记)

外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
外观模式完美的体现了依赖倒转原则和迪米特法则的思想,所以是比较常见的设计模式之一。
外观模式结构图如下:
设计模式之外观(Facade)方式(笔记)

定义三个子系统类

public class SubSystemOne {

    public void methodOne(){
        System.out.println("子系统方法1");
    }
}

public class SubSystemTwo {

    public void methodTwo(){
        System.out.println("子系统方法2");
    }
}

public class SubSystemThree {

    public void methodThree(){
        System.out.println("子系统方法3");
    }
}

定义一个外观Facade类

public class Facade {

    private SubSystemOne one;
    private SubSystemTwo two;
    private SubSystemThree three;

    public Facade(){
        one =new SubSystemOne();
        two=new SubSystemTwo();
        three=new SubSystemThree();
    }

    public void methodA(){
        one.methodOne();
        three.methodThree();
    }

    public void methodB(){
        one.methodOne();
        two.methodTwo();
    }
}

客户端代码

public static void main(String[] args) {

        Facade facade=new Facade();
        facade.methodA();
        facade.methodB();
}

由于Facade类的作用,客户端可以根本不知道三个子系统的存在