博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java设计模式之Facade模式
阅读量:2153 次
发布时间:2019-04-30

本文共 1494 字,大约阅读时间需要 4 分钟。

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

假设我们现有一个对外接口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不该访问到的方法等等。
 

转载地址:http://ttswb.baihongyu.com/

你可能感兴趣的文章
PAT1090 Highest Price in Supply Chain 树DFS
查看>>
(PAT 1096) Consecutive Factors (质因子分解)
查看>>
(PAT 1019) General Palindromic Number (进制转换)
查看>>
(PAT 1073) Scientific Notation (字符串模拟题)
查看>>
(PAT 1080) Graduate Admission (排序)
查看>>
Play on Words UVA - 10129 (欧拉路径)
查看>>
mininet+floodlight搭建sdn环境并创建简答topo
查看>>
【linux】nohup和&的作用
查看>>
Set、WeakSet、Map以及WeakMap结构基本知识点
查看>>
【NLP学习笔记】(一)Gensim基本使用方法
查看>>
【NLP学习笔记】(二)gensim使用之Topics and Transformations
查看>>
【深度学习】LSTM的架构及公式
查看>>
【python】re模块常用方法
查看>>
剑指offer 19.二叉树的镜像
查看>>
剑指offer 20.顺时针打印矩阵
查看>>
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>
剑指offer 60. 不用加减乘除做加法
查看>>
Leetcode C++《热题 Hot 100-13》234.回文链表
查看>>