外观模式(Facade Pattern)

外观模式(Facade Pattern) ,为子系统中的一组接口提供一个一致的页面,此模式定义一个高层接口,这个接口使这一子系统更加容易使用。

  简单说,就是用一个外观类引用其他对象,在外观类的方法中调用多个其他对象的方法。

 

外观模式使用起来简单,平时写代码中,也许已经使用过这个模式写代码。下面看代码。

1,新建三个类,各有一个方法。

public class SubSystemOne {
    public void methodOne(){
        System.out.println("MethodOne");
    }
}
public class SubSystemTwo {
    public void methodTwo(){
        System.out.println("MethodTwo");
    }
}
public class SubSystemThree {
    public void methodThree(){
        System.out.println("MethodThree");
    }
}

 2,新建一个外观类,包含上面三个类对象,对外提供组合方法

public class Facade {
    SubSystemOne one;
    SubSystemTwo two;
    SubSystemThree three;

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

    public void MethodA(){  //方法组1
        one.methodOne();
        two.methodTwo();
    }

    public void MethodB(){  //方法组2
        two.methodTwo();
        three.methodThree();
    }
}

 

3,调用外观对象方法

public class FacadePattern {
    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.MethodA();
        facade.MethodB();
    }
}

 

 

一般什么时候使用外观类?

  现在流行的三层架构,业务层(service)可能会引用多个持久层(dao层)的对象,以便获得数据处理业务逻辑。controller层直接调用service层就可以了,而不需要直接和多个持久层进行交互。

posted @ 2018-12-19 16:31  dioag  阅读(132)  评论(0编辑  收藏  举报