java设计模式之Facade模式

介绍外观模式之前,首先让我们来看下面的例子:

假设我们现有一个对外接口FacadeService,里面有一个对外的方法a();

public interface FacadeService {

    public void a();//这个方法是给外部调用的
}

他有一个实现类FacadeServiceImpl,他实现了FacadeService接口的a方法,同时又新增了一个自己的供内部调用的方法b;

public class FacadeServiceImpl implements FacadeService {
    public void a() {
        System.out.println("这是给外部调用的");
    }

    public void b() {
        System.out.println("这是给内部调用的");
    }
}

此时我们再模拟外部调用的逻辑

public class FacadeServiceMain {
    public static void main(String[] args) {
        FacadeServiceImpl facadeService = new FacadeServiceImpl();
        facadeService.a();
        facadeService.b();
    }
}

因为a是给外部调用用的,此时可以给外部调用,但是b是给内部调用的,我们不希望给外部调用,此时我们可以怎么做呢?有的人说,可以调整b方法的访问权限,使得只能只能同一个包下面的类可以访问,除了这个方法之外还有别的更优雅的方法吗?请看下面的例子:

public class FacadeServiceImplForOut implements FacadeService {


    private FacadeService facadeService;

    public FacadeServiceImplForOut(FacadeServiceImpl facadeService){
        this.facadeService=facadeService;
    }
    public void a() {
        facadeService.a();
    }


}
此时FacadeServer对象是一个私有的对象,他只能在本类访问,同时他实现了FacaseServer接口,提供了能供外部访问的方法a,这样是不是实现了外部只能访问a方法的改造? 
 
public class FacadeServiceMain {
    public static void main(String[] args) {
       /* FacadeServiceImpl facadeService = new FacadeServiceImpl();
        facadeService.a();
        facadeService.b();*/

        FacadeServiceImpl facadeService = new FacadeServiceImpl();
        FacadeServiceImplForOut fout = new FacadeServiceImplForOut(facadeService);
        fout.a();
    }
}
 
 

这就是facade(外观模式),他提供了一个供外部client调用的层Facade,由Facade层去组织调用真正的业务层,对于调用client来说,真正的业务层对他来说是透明的,这样做的好处是让调用层client和真正的业务层解耦,同时在Facade层也可以做更多的事情,比如上面的屏蔽client不该访问到的方法等等

猜你喜欢

转载自blog.csdn.net/chengkui1990/article/details/80925683