结构型模式描述如何将类或对象按某种布局组成更大的结构。它分为类结构型模式和对象结构型模式,前者采用继承机制来组织接口和类,后者釆用组合或聚合来组合对象。
由于组合关系或聚合关系比继承关系耦合度低,满足“合成复用原则”,所以对象结构型模式比类结构型模式具有更大的灵活性。
结构型模式分为以下 7 种:
由于某些原因需要给某对象提供一个代理以控制对该对象的访问。这时,访问对象不适合或者不能直接引用目标对象,代理对象作为访问对象和目标对象之间的中介。
Java中的代理按照代理类生成时机不同又分为静态代理和动态代理。静态代理代理类在编译期就生成,而动态代理代理类则是在Java运行时动态生成。动态代理又有JDK代理和CGLib代理两种。
代理(Proxy)模式分为三种角色:
我们通过案例来感受一下静态代理。
【例】火车站卖票
如果要买火车票的话,需要去火车站买票,坐车到火车站,排队等一系列的操作,显然比较麻烦。而火车站在多个地方都有代售点,我们去代售点买票就方便很多了。这个例子其实就是典型的代理模式,火车站是目标对象,代售点是代理对象。类图如下:

代码如下:
x1//卖票接口2public interface SellTickets {3 void sell();4}56//火车站 火车站具有卖票功能,所以需要实现SellTickets接口7public class TrainStation implements SellTickets {89 public void sell() {10 System.out.println("火车站卖票");11 }12}1314//代售点15public class ProxyPoint implements SellTickets {1617 private TrainStation station = new TrainStation();1819 public void sell() {20 System.out.println("代理点收取一些服务费用");21 station.sell();22 }23}2425//测试类26public class Client {27 public static void main(String[] args) {28 ProxyPoint pp = new ProxyPoint();29 pp.sell();30 }31}从上面代码中可以看出测试类直接访问的是ProxyPoint类对象,也就是说ProxyPoint作为访问对象和目标对象的中介。同时也对sell方法进行了增强(代理点收取一些服务费用)。
接下来我们使用动态代理实现上面案例,先说说JDK提供的动态代理。Java中提供了一个动态代理类Proxy,Proxy并不是我们上述所说的代理对象的类,而是提供了一个创建代理对象的静态方法(newProxyInstance方法)来获取代理对象。
代码如下:
xxxxxxxxxx571//卖票接口2public interface SellTickets {3 void sell();4}56//火车站 火车站具有卖票功能,所以需要实现SellTickets接口7public class TrainStation implements SellTickets {89 public void sell() {10 System.out.println("火车站卖票");11 }12}1314//代理工厂,用来创建代理对象15public class ProxyFactory {1617 private TrainStation station = new TrainStation();1819 public SellTickets getProxyObject() {20 //使用Proxy获取代理对象21 /*22 newProxyInstance()方法参数说明:23 ClassLoader loader : 类加载器,用于加载代理类,使用真实对象的类加载器即可24 Class<?>[] interfaces : 真实对象所实现的接口,代理模式真实对象和代理对象实现相同的接口25 InvocationHandler h : 代理对象的调用处理程序26 */27 SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(station.getClass().getClassLoader(),28 station.getClass().getInterfaces(),29 new InvocationHandler() {30 /*31 InvocationHandler中invoke方法参数说明:32 proxy : 代理对象33 method : 对应于在代理对象上调用的接口方法的 Method 实例34 args : 代理对象调用接口方法时传递的实际参数35 */36 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {3738 System.out.println("代理点收取一些服务费用(JDK动态代理方式)");39 //执行真实对象40 Object result = method.invoke(station, args);41 return result;42 }43 });44 return sellTickets;45 }46}4748//测试类49public class Client {50 public static void main(String[] args) {51 //获取代理对象52 ProxyFactory factory = new ProxyFactory();53 54 SellTickets proxyObject = factory.getProxyObject();55 proxyObject.sell();56 }57}使用了动态代理,我们思考下面问题:
ProxyFactory是代理类吗?
ProxyFactory不是代理模式中所说的代理类,而代理类是程序在运行过程中动态的在内存中生成的类。通过阿里巴巴开源的 Java 诊断工具(Arthas【阿尔萨斯】)查看代理类的结构:
xxxxxxxxxx831package com.sun.proxy;23import com.itheima.proxy.dynamic.jdk.SellTickets;4import java.lang.reflect.InvocationHandler;5import java.lang.reflect.Method;6import java.lang.reflect.Proxy;7import java.lang.reflect.UndeclaredThrowableException;89public final class $Proxy0 extends Proxy implements SellTickets {10 private static Method m1;11 private static Method m2;12 private static Method m3;13 private static Method m0;1415 public $Proxy0(InvocationHandler invocationHandler) {16 super(invocationHandler);17 }1819 static {20 try {21 m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));22 m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);23 m3 = Class.forName("com.itheima.proxy.dynamic.jdk.SellTickets").getMethod("sell", new Class[0]);24 m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);25 return;26 }27 catch (NoSuchMethodException noSuchMethodException) {28 throw new NoSuchMethodError(noSuchMethodException.getMessage());29 }30 catch (ClassNotFoundException classNotFoundException) {31 throw new NoClassDefFoundError(classNotFoundException.getMessage());32 }33 }3435 public final boolean equals(Object object) {36 try {37 return (Boolean)this.h.invoke(this, m1, new Object[]{object});38 }39 catch (Error | RuntimeException throwable) {40 throw throwable;41 }42 catch (Throwable throwable) {43 throw new UndeclaredThrowableException(throwable);44 }45 }4647 public final String toString() {48 try {49 return (String)this.h.invoke(this, m2, null);50 }51 catch (Error | RuntimeException throwable) {52 throw throwable;53 }54 catch (Throwable throwable) {55 throw new UndeclaredThrowableException(throwable);56 }57 }5859 public final int hashCode() {60 try {61 return (Integer)this.h.invoke(this, m0, null);62 }63 catch (Error | RuntimeException throwable) {64 throw throwable;65 }66 catch (Throwable throwable) {67 throw new UndeclaredThrowableException(throwable);68 }69 }7071 public final void sell() {72 try {73 this.h.invoke(this, m3, null);74 return;75 }76 catch (Error | RuntimeException throwable) {77 throw throwable;78 }79 catch (Throwable throwable) {80 throw new UndeclaredThrowableException(throwable);81 }82 }83}从上面的类中,我们可以看到以下几个信息:
动态代理的执行流程是什么样?
下面是摘取的重点代码:
xxxxxxxxxx571//程序运行过程中动态生成的代理类2public final class $Proxy0 extends Proxy implements SellTickets {3 private static Method m3;45 public $Proxy0(InvocationHandler invocationHandler) {6 super(invocationHandler);7 }89 static {10 m3 = Class.forName("com.itheima.proxy.dynamic.jdk.SellTickets").getMethod("sell", new Class[0]);11 }1213 public final void sell() {14 this.h.invoke(this, m3, null);15 }16}1718//Java提供的动态代理相关类19public class Proxy implements java.io.Serializable {20 protected InvocationHandler h;21 22 protected Proxy(InvocationHandler h) {23 this.h = h;24 }25}2627//代理工厂类28public class ProxyFactory {2930 private TrainStation station = new TrainStation();3132 public SellTickets getProxyObject() {33 SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(station.getClass().getClassLoader(),34 station.getClass().getInterfaces(),35 new InvocationHandler() {36 37 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {3839 System.out.println("代理点收取一些服务费用(JDK动态代理方式)");40 Object result = method.invoke(station, args);41 return result;42 }43 });44 return sellTickets;45 }46}474849//测试访问类50public class Client {51 public static void main(String[] args) {52 //获取代理对象53 ProxyFactory factory = new ProxyFactory();54 SellTickets proxyObject = factory.getProxyObject();55 proxyObject.sell();56 }57}执行流程如下:
同样是上面的案例,我们再次使用CGLIB代理实现。
如果没有定义SellTickets接口,只定义了TrainStation(火车站类)。很显然JDK代理是无法使用了,因为JDK动态代理要求必须定义接口,对接口进行代理。
CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。
CGLIB是第三方提供的包,所以需要引入jar包的坐标:
xxxxxxxxxx51<dependency>2 <groupId>cglib</groupId>3 <artifactId>cglib</artifactId>4 <version>2.2.2</version>5</dependency>代码如下:
xxxxxxxxxx501//火车站2public class TrainStation {34 public void sell() {5 System.out.println("火车站卖票");6 }7}89//代理工厂10public class ProxyFactory implements MethodInterceptor {1112 private TrainStation target = new TrainStation();1314 public TrainStation getProxyObject() {15 //创建Enhancer对象,类似于JDK动态代理的Proxy类,下一步就是设置几个参数16 Enhancer enhancer =new Enhancer();17 //设置父类的字节码对象18 enhancer.setSuperclass(target.getClass());19 //设置回调函数20 enhancer.setCallback(this);21 //创建代理对象22 TrainStation obj = (TrainStation) enhancer.create();23 return obj;24 }2526 /*27 intercept方法参数说明:28 o : 代理对象29 method : 真实对象中的方法的Method实例30 args : 实际参数31 methodProxy :代理对象中的方法的method实例32 */33 public TrainStation intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {34 System.out.println("代理点收取一些服务费用(CGLIB动态代理方式)");35 TrainStation result = (TrainStation) methodProxy.invokeSuper(o, args);36 return result;37 }38}3940//测试类41public class Client {42 public static void main(String[] args) {43 //创建代理工厂对象44 ProxyFactory factory = new ProxyFactory();45 //获取代理对象46 TrainStation proxyObject = factory.getProxyObject();4748 proxyObject.sell();49 }50}jdk代理和CGLIB代理
使用CGLib实现动态代理,CGLib底层采用ASM字节码生成框架,使用字节码技术生成代理类,在JDK1.6之前比使用Java反射效率要高。唯一需要注意的是,CGLib不能对声明为final的类或者方法进行代理,因为CGLib原理是动态生成被代理类的子类。
在JDK1.6、JDK1.7、JDK1.8逐步对JDK动态代理优化之后,在调用次数较少的情况下,JDK代理效率高于CGLib代理效率,只有当进行大量调用的时候,JDK1.6和JDK1.7比CGLib代理效率低一点,但是到JDK1.8的时候,JDK代理效率高于CGLib代理。所以如果有接口使用JDK动态代理,如果没有接口使用CGLIB代理。
动态代理和静态代理
动态代理与静态代理相比较,最大的好处是接口中声明的所有方法都被转移到调用处理器一个集中的方法中处理(InvocationHandler.invoke)。这样,在接口方法数量比较多的时候,我们可以进行灵活处理,而不需要像静态代理那样每一个方法进行中转。
如果接口增加一个方法,静态代理模式除了所有实现类需要实现这个方法外,所有代理类也需要实现此方法。增加了代码维护的复杂度。而动态代理不会出现该问题
优点:
缺点:
远程(Remote)代理
本地服务通过网络请求远程服务。为了实现本地到远程的通信,我们需要实现网络通信,处理其中可能的异常。为良好的代码设计和可维护性,我们将网络通信部分隐藏起来,只暴露给本地服务一个接口,通过该接口即可访问远程服务提供的功能,而不必过多关心通信部分的细节。
防火墙(Firewall)代理
当你将浏览器配置成使用代理功能时,防火墙就将你的浏览器的请求转给互联网;当互联网返回响应时,代理服务器再把它转给你的浏览器。
保护(Protect or Access)代理
控制对一个对象的访问,如果需要,可以给不同的用户提供不同级别的使用权限。
如果去欧洲国家去旅游的话,他们的插座如下图最左边,是欧洲标准。而我们使用的插头如下图最右边的。因此我们的笔记本电脑,手机在当地不能直接充电。所以就需要一个插座转换器,转换器第1面插入当地的插座,第2面供我们充电,这样使得我们的插头在当地能使用。生活中这样的例子很多,手机充电器(将220v转换为5v的电压),读卡器等,其实就是使用到了适配器模式。

定义:
将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
适配器模式分为类适配器模式和对象适配器模式,前者类之间的耦合度比后者高,且要求程序员了解现有组件库中的相关组件的内部结构,所以应用相对较少些。
适配器模式(Adapter)包含以下主要角色:
实现方式:定义一个适配器类来实现当前系统的业务接口,同时又继承现有组件库中已经存在的组件。
【例】读卡器
现有一台电脑只能读取SD卡,而要读取TF卡中的内容的话就需要使用到适配器模式。创建一个读卡器,将TF卡中的内容读取出来。
类图如下:

代码如下:
xxxxxxxxxx791//SD卡的接口2public interface SDCard {3 //读取SD卡方法4 String readSD();5 //写入SD卡功能6 void writeSD(String msg);7}89//SD卡实现类10public class SDCardImpl implements SDCard {11 public String readSD() {12 String msg = "sd card read a msg :hello word SD";13 return msg;14 }1516 public void writeSD(String msg) {17 System.out.println("sd card write msg : " + msg);18 }19}2021//电脑类22public class Computer {2324 public String readSD(SDCard sdCard) {25 if(sdCard == null) {26 throw new NullPointerException("sd card null");27 }28 return sdCard.readSD();29 }30}3132//TF卡接口33public interface TFCard {34 //读取TF卡方法35 String readTF();36 //写入TF卡功能37 void writeTF(String msg);38}3940//TF卡实现类41public class TFCardImpl implements TFCard {4243 public String readTF() {44 String msg ="tf card read msg : hello word tf card";45 return msg;46 }4748 public void writeTF(String msg) {49 System.out.println("tf card write a msg : " + msg);50 }51}5253//定义适配器类(SD兼容TF)54public class SDAdapterTF extends TFCardImpl implements SDCard {5556 public String readSD() {57 System.out.println("adapter read tf card ");58 return readTF();59 }6061 public void writeSD(String msg) {62 System.out.println("adapter write tf card");63 writeTF(msg);64 }65}6667//测试类68public class Client {69 public static void main(String[] args) {70 Computer computer = new Computer();71 SDCard sdCard = new SDCardImpl();72 System.out.println(computer.readSD(sdCard));7374 System.out.println("------------");7576 SDAdapterTF adapter = new SDAdapterTF();77 System.out.println(computer.readSD(adapter));78 }79}类适配器模式违背了合成复用原则。类适配器是客户类有一个接口规范的情况下可用,反之不可用。
实现方式:对象适配器模式可釆用将现有组件库中已经实现的组件引入适配器类中,该类同时实现当前系统的业务接口。
【例】读卡器
我们使用对象适配器模式将读卡器的案例进行改写。类图如下:

代码如下:
类适配器模式的代码,我们只需要修改适配器类(SDAdapterTF)和测试类。
xxxxxxxxxx341//创建适配器对象(SD兼容TF)2public class SDAdapterTF implements SDCard {34 private TFCard tfCard;56 public SDAdapterTF(TFCard tfCard) {7 this.tfCard = tfCard;8 }910 public String readSD() {11 System.out.println("adapter read tf card ");12 return tfCard.readTF();13 }1415 public void writeSD(String msg) {16 System.out.println("adapter write tf card");17 tfCard.writeTF(msg);18 }19}2021//测试类22public class Client {23 public static void main(String[] args) {24 Computer computer = new Computer();25 SDCard sdCard = new SDCardImpl();26 System.out.println(computer.readSD(sdCard));2728 System.out.println("------------");2930 TFCard tfCard = new TFCardImpl();31 SDAdapterTF adapter = new SDAdapterTF(tfCard);32 System.out.println(computer.readSD(adapter));33 }34}注意:还有一个适配器模式是接口适配器模式。当不希望实现一个接口中所有的方法时,可以创建一个抽象类Adapter ,实现所有方法。而此时我们只需要继承该抽象类即可。
Reader(字符流)、InputStream(字节流)的适配使用的是InputStreamReader。
InputStreamReader继承自java.io包中的Reader,对他中的抽象的未实现的方法给出实现。如:
xxxxxxxxxx71public int read() throws IOException {2 return sd.read();3}45public int read(char cbuf[], int offset, int length) throws IOException {6 return sd.read(cbuf, offset, length);7}如上代码中的sd(StreamDecoder类对象),在Sun的JDK实现中,实际的方法实现是对sun.nio.cs.StreamDecoder类的同名方法的调用封装。类结构图如下:

从上图可以看出:
结论:
从表层来看,InputStreamReader做了InputStream字节流类到Reader字符流之间的转换。而从如上Sun JDK中的实现类关系结构中可以看出,是StreamDecoder的设计实现在实际上采用了适配器模式。
我们先来看一个快餐店的例子。
快餐店有炒面、炒饭这些快餐,可以额外附加鸡蛋、火腿、培根这些配菜,当然加配菜需要额外加钱,每个配菜的价钱通常不太一样,那么计算总价就会显得比较麻烦。

使用继承的方式存在的问题:
扩展性不好
如果要再加一种配料(火腿肠),我们就会发现需要给FriedRice和FriedNoodles分别定义一个子类。如果要新增一个快餐品类(炒河粉)的话,就需要定义更多的子类。
产生过多的子类
定义:
指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式。
装饰(Decorator)模式中的角色:
我们使用装饰者模式对快餐店案例进行改进,体会装饰者模式的精髓。
类图如下:

代码如下:
xxxxxxxxxx1351//快餐接口2public abstract class FastFood {3 private float price;4 private String desc;56 public FastFood() {7 }89 public FastFood(float price, String desc) {10 this.price = price;11 this.desc = desc;12 }1314 public void setPrice(float price) {15 this.price = price;16 }1718 public float getPrice() {19 return price;20 }2122 public String getDesc() {23 return desc;24 }2526 public void setDesc(String desc) {27 this.desc = desc;28 }2930 public abstract float cost(); //获取价格31}3233//炒饭34public class FriedRice extends FastFood {3536 public FriedRice() {37 super(10, "炒饭");38 }3940 public float cost() {41 return getPrice();42 }43}4445//炒面46public class FriedNoodles extends FastFood {4748 public FriedNoodles() {49 super(12, "炒面");50 }5152 public float cost() {53 return getPrice();54 }55}5657//配料类58public abstract class Garnish extends FastFood {5960 private FastFood fastFood;6162 public FastFood getFastFood() {63 return fastFood;64 }6566 public void setFastFood(FastFood fastFood) {67 this.fastFood = fastFood;68 }6970 public Garnish(FastFood fastFood, float price, String desc) {71 super(price,desc);72 this.fastFood = fastFood;73 }74}7576//鸡蛋配料77public class Egg extends Garnish {7879 public Egg(FastFood fastFood) {80 super(fastFood,1,"鸡蛋");81 }8283 public float cost() {84 return getPrice() + getFastFood().getPrice();85 }8687 88 public String getDesc() {89 return super.getDesc() + getFastFood().getDesc();90 }91}9293//培根配料94public class Bacon extends Garnish {9596 public Bacon(FastFood fastFood) {9798 super(fastFood,2,"培根");99 }100101 102 public float cost() {103 return getPrice() + getFastFood().getPrice();104 }105106 107 public String getDesc() {108 return super.getDesc() + getFastFood().getDesc();109 }110}111112//测试类113public class Client {114 public static void main(String[] args) {115 //点一份炒饭116 FastFood food = new FriedRice();117 //花费的价格118 System.out.println(food.getDesc() + " " + food.cost() + "元");119120 System.out.println("========");121 //点一份加鸡蛋的炒饭122 FastFood food1 = new FriedRice();123124 food1 = new Egg(food1);125 //花费的价格126 System.out.println(food1.getDesc() + " " + food1.cost() + "元");127128 System.out.println("========");129 //点一份加培根的炒面130 FastFood food2 = new FriedNoodles();131 food2 = new Bacon(food2);132 //花费的价格133 System.out.println(food2.getDesc() + " " + food2.cost() + "元");134 }135}好处:
当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。
不能采用继承的情况主要有两类:
在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
当对象的功能要求可以动态地添加,也可以再动态地撤销时。
IO流中的包装类使用到了装饰者模式。BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter。
我们以BufferedWriter举例来说明,先看看如何使用BufferedWriter
xxxxxxxxxx131public class Demo {2 public static void main(String[] args) throws Exception{3 //创建BufferedWriter对象4 //创建FileWriter对象5 FileWriter fw = new FileWriter("C:\\Users\\Think\\Desktop\\a.txt");6 BufferedWriter bw = new BufferedWriter(fw);78 //写数据9 bw.write("hello Buffered");1011 bw.close();12 }13}使用起来感觉确实像是装饰者模式,接下来看它们的结构:

小结:
BufferedWriter使用装饰者模式对Writer子实现类进行了增强,添加了缓冲区,提高了写数据的效率。
静态代理和装饰者模式的区别:
相同点:
不同点:
现在有一个需求,需要创建不同的图形,并且每个图形都有可能会有不同的颜色。我们可以利用继承的方式来设计类的关系:

我们可以发现有很多的类,假如我们再增加一个形状或再增加一种颜色,就需要创建更多的类。
试想,在一个有多种可能会变化的维度的系统中,用继承方式会造成类爆炸,扩展起来不灵活。每次在一个维度上新增一个具体实现都要增加多个子类。为了更加灵活的设计系统,我们此时可以考虑使用桥接模式。
定义:
将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
桥接(Bridge)模式包含以下主要角色:
【例】视频播放器
需要开发一个跨平台视频播放器,可以在不同操作系统平台(如Windows、Mac、Linux等)上播放多种格式的视频文件,常见的视频格式包括RMVB、AVI、WMV等。该播放器包含了两个维度,适合使用桥接模式。
类图如下:

代码如下:
xxxxxxxxxx631//视频文件2public interface VideoFile {3 void decode(String fileName);4}56//avi文件7public class AVIFile implements VideoFile {8 public void decode(String fileName) {9 System.out.println("avi视频文件:"+ fileName);10 }11}1213//rmvb文件14public class REVBBFile implements VideoFile {1516 public void decode(String fileName) {17 System.out.println("rmvb文件:" + fileName);18 }19}2021//操作系统版本22public abstract class OperatingSystemVersion {2324 protected VideoFile videoFile;2526 public OperatingSystemVersion(VideoFile videoFile) {27 this.videoFile = videoFile;28 }2930 public abstract void play(String fileName);31}3233//Windows版本34public class Windows extends OperatingSystem {3536 public Windows(VideoFile videoFile) {37 super(videoFile);38 }3940 public void play(String fileName) {41 videoFile.decode(fileName);42 }43}4445//mac版本46public class Mac extends OperatingSystemVersion {4748 public Mac(VideoFile videoFile) {49 super(videoFile);50 }5152 public void play(String fileName) {53 videoFile.decode(fileName);54 }55}5657//测试类58public class Client {59 public static void main(String[] args) {60 OperatingSystem os = new Windows(new AVIFile());61 os.play("战狼3");62 }63}好处:
桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。
如:如果现在还有一种视频文件类型wmv,我们只需要再定义一个类实现VideoFile接口即可,其他类不需要发生变化。
实现细节对客户透明
有些人可能炒过股票,但其实大部分人都不太懂,这种没有足够了解证券知识的情况下做股票是很容易亏钱的,刚开始炒股肯定都会想,如果有个懂行的帮帮手就好,其实基金就是个好帮手,支付宝里就有许多的基金,它将投资者分散的资金集中起来,交由专业的经理人进行管理,投资于股票、债券、外汇等领域,而基金投资的收益归持有者所有,管理机构收取一定比例的托管管理费用。
定义:
又名门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。该模式对外有一个统一接口,外部应用程序不用关心内部子系统的具体的细节,这样会大大降低应用程序的复杂度,提高了程序的可维护性。
外观(Facade)模式是“迪米特法则”的典型应用

外观(Facade)模式包含以下主要角色:
【例】智能家电控制
小明的爷爷已经60岁了,一个人在家生活:每次都需要打开灯、打开电视、打开空调;睡觉时关闭灯、关闭电视、关闭空调;操作起来都比较麻烦。所以小明给爷爷买了智能音箱,可以通过语音直接控制这些智能家电的开启和关闭。类图如下:

代码如下:
xxxxxxxxxx831//灯类2public class Light {3 public void on() {4 System.out.println("打开了灯....");5 }67 public void off() {8 System.out.println("关闭了灯....");9 }10}1112//电视类13public class TV {14 public void on() {15 System.out.println("打开了电视....");16 }1718 public void off() {19 System.out.println("关闭了电视....");20 }21}2223//控制类24public class AirCondition {25 public void on() {26 System.out.println("打开了空调....");27 }2829 public void off() {30 System.out.println("关闭了空调....");31 }32}3334//智能音箱35public class SmartAppliancesFacade {3637 private Light light;38 private TV tv;39 private AirCondition airCondition;4041 public SmartAppliancesFacade() {42 light = new Light();43 tv = new TV();44 airCondition = new AirCondition();45 }4647 public void say(String message) {48 if(message.contains("打开")) {49 on();50 } else if(message.contains("关闭")) {51 off();52 } else {53 System.out.println("我还听不懂你说的!!!");54 }55 }5657 //起床后一键开电器58 private void on() {59 System.out.println("起床了");60 light.on();61 tv.on();62 airCondition.on();63 }6465 //睡觉一键关电器66 private void off() {67 System.out.println("睡觉了");68 light.off();69 tv.off();70 airCondition.off();71 }72}7374//测试类75public class Client {76 public static void main(String[] args) {77 //创建外观对象78 SmartAppliancesFacade facade = new SmartAppliancesFacade();79 //客户端直接与外观对象进行交互80 facade.say("打开家电");81 facade.say("关闭家电");82 }83}好处:
缺点:
使用tomcat作为web容器时,接收浏览器发送过来的请求,tomcat会将请求信息封装成ServletRequest对象,如下图①处对象。但是大家想想ServletRequest是一个接口,它还有一个子接口HttpServletRequest,而我们知道该request对象肯定是一个HttpServletRequest对象的子实现类对象,到底是哪个类的对象呢?可以通过输出request对象,我们就会发现是一个名为RequestFacade的类的对象。

RequestFacade类就使用了外观模式。先看结构图:

为什么在此处使用外观模式呢?
定义 RequestFacade 类,分别实现 ServletRequest ,同时定义私有成员变量 Request ,并且方法的实现调用 Request 的实现。然后,将 RequestFacade上转为 ServletRequest 传给 servlet 的 service 方法,这样即使在 servlet 中被下转为 RequestFacade ,也不能访问私有成员变量对象中的方法。既用了 Request ,又能防止其中方法被不合理的访问。