五、外观模式
1 外观模式?
创建外观类,封装复杂子系统的实现细节,对外提供新的简单接口。
记忆方法:仍然是通过外观类的构造方法注入子系统类。
2 应用场景?
- 比如MVC架构,层与层之间通过外观模式对外提供接口,隐藏复杂子系统的实现细节。这样可以达到层与层之间松耦合的效果。 随着开发,子系统不断的复杂化的时候,只需要修改对外的接口即可。
- 在维护一个遗留的大型项目时,可能这个系统已经很难以维护和扩展了。但新的系统又需要依赖老系统的核心方法。 这时,为老系统开发一个外观类,外观类包含老系统的核心方法,对新系统提供新的简单接口去供新系统调用。
3 demo?
package com.biao.surface; public class SurfaceDemo { public static void main(String[] args) { Surface surface = new Surface(); surface.methodA(); surface.methodB(); } } //定义四个子系统,每个子系统中有各自的实现方法 class SubSystemone{ public void methodOne(){ System.out.println("子系统1方法"); } } class SubSystemtwo{ public void methodTwo(){ System.out.println("子系统2方法"); } } class SubSystemthree{ public void methodThree(){ System.out.println("子系统3方法"); } } class SubSystemFour{ public void methodFour(){ System.out.println("子系统4方法"); } } //定义高级类,实现对子系统封装(就是维护子类对象的引用,通过对子类对象的引用去调用子类的方法)对外提供接口方法。 class Surface{ SubSystemone one; SubSystemtwo two; SubSystemthree three; SubSystemFour four; public Surface() { // TODO Auto-generated constructor stub one = new SubSystemone(); two = new SubSystemtwo(); three = new SubSystemthree(); four = new SubSystemFour(); } //编写对外接口方法,具体one.methodOne();如何实现的,不对外公布。隐藏子系统的实现细节。 public void methodA(){ System.out.println("该方法是更高层的类提供的方法1,它封装了子系统方法:"); one.methodOne(); two.methodTwo(); } public void methodB(){ System.out.println("该方法是更高层的类封装的方法2,它封装了子系统方法:"); three.methodThree(); four.methodFour(); } }