Java的23种设计模式,详细讲解(三)
本人免费整理了java高级资料,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo高并发分布式等教程,一共30g,需要自己领取。
传送门:https://mp.weixin.qq.com/s/jzddfh-7ynudmkjt0irl8q
1. 适配器(adapter)
intent
把一个类接口转换成另一个用户需要的接口。
class diagram
implementation
鸭子(duck)和火鸡(turkey)拥有不同的叫声,duck 的叫声调用 quack() 方法,而 turkey 调用 gobble() 方法。
要求将 turkey 的 gobble() 方法适配成 duck 的 quack() 方法,从而让火鸡冒充鸭子!
public interface duck { void quack(); } public interface turkey { void gobble(); } public class wildturkey implements turkey { @override public void gobble() { system.out.println("gobble!"); } } public class turkeyadapter implements duck { turkey turkey; public turkeyadapter(turkey turkey) { this.turkey = turkey; } @override public void quack() { turkey.gobble(); } } public class client { public static void main(string[] args) { turkey turkey = new wildturkey(); duck duck = new turkeyadapter(turkey); duck.quack(); } }
jdk
- java.util.arrays#aslist()
- java.util.collections#list()
- java.util.collections#enumeration()
- javax.xml.bind.annotation.adapters.xmladapter
2. 桥接(bridge)
intent
将抽象与实现分离开来,使它们可以独立变化。
class diagram
- abstraction:定义抽象类的接口
- implementor:定义实现类接口
implementation
remotecontrol 表示遥控器,指代 abstraction。
tv 表示电视,指代 implementor。
桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。
public abstract class tv { public abstract void on(); public abstract void off(); public abstract void tunechannel(); } public class sony extends tv { @override public void on() { system.out.println("sony.on()"); } @override public void off() { system.out.println("sony.off()"); } @override public void tunechannel() { system.out.println("sony.tunechannel()"); } } public class rca extends tv { @override public void on() { system.out.println("rca.on()"); } @override public void off() { system.out.println("rca.off()"); } @override public void tunechannel() { system.out.println("rca.tunechannel()"); } } public abstract class remotecontrol { protected tv tv; public remotecontrol(tv tv) { this.tv = tv; } public abstract void on(); public abstract void off(); public abstract void tunechannel(); } public class concreteremotecontrol1 extends remotecontrol { public concreteremotecontrol1(tv tv) { super(tv); } @override public void on() { system.out.println("concreteremotecontrol1.on()"); tv.on(); } @override public void off() { system.out.println("concreteremotecontrol1.off()"); tv.off(); } @override public void tunechannel() { system.out.println("concreteremotecontrol1.tunechannel()"); tv.tunechannel(); } } public class concreteremotecontrol2 extends remotecontrol { public concreteremotecontrol2(tv tv) { super(tv); } @override public void on() { system.out.println("concreteremotecontrol2.on()"); tv.on(); } @override public void off() { system.out.println("concreteremotecontrol2.off()"); tv.off(); } @override public void tunechannel() { system.out.println("concreteremotecontrol2.tunechannel()"); tv.tunechannel(); } } public class client { public static void main(string[] args) { remotecontrol remotecontrol1 = new concreteremotecontrol1(new rca()); remotecontrol1.on(); remotecontrol1.off(); remotecontrol1.tunechannel(); remotecontrol remotecontrol2 = new concreteremotecontrol2(new sony()); remotecontrol2.on(); remotecontrol2.off(); remotecontrol2.tunechannel(); } }
jdk
- awt (it provides an abstraction layer which maps onto the native os the windowing support.)
- jdbc
3. 组合(composite)
intent
将对象组合成树形结构来表示“整体/部分”层次关系,允许用户以相同的方式处理单独对象和组合对象。
class diagram
组件(component)类是组合类(composite)和叶子类(leaf)的父类,可以把组合类看成是树的中间节点。
组合对象拥有一个或者多个组件对象,因此组合对象的操作可以委托给组件对象去处理,而组件对象可以是另一个组合对象或者叶子对象。
implementation
public abstract class component { protected string name; public component(string name) { this.name = name; } public void print() { print(0); } abstract void print(int level); abstract public void add(component component); abstract public void remove(component component); } public class composite extends component { private list<component> child; public composite(string name) { super(name); child = new arraylist<>(); } @override void print(int level) { for (int i = 0; i < level; i++) { system.out.print("--"); } system.out.println("composite:" + name); for (component component : child) { component.print(level + 1); } } @override public void add(component component) { child.add(component); } @override public void remove(component component) { child.remove(component); } } public class leaf extends component { public leaf(string name) { super(name); } @override void print(int level) { for (int i = 0; i < level; i++) { system.out.print("--"); } system.out.println("left:" + name); } @override public void add(component component) { throw new unsupportedoperationexception(); // 牺牲透明性换取单一职责原则,这样就不用考虑是叶子节点还是组合节点 } @override public void remove(component component) { throw new unsupportedoperationexception(); } } public class client { public static void main(string[] args) { composite root = new composite("root"); component node1 = new leaf("1"); component node2 = new composite("2"); component node3 = new leaf("3"); root.add(node1); root.add(node2); root.add(node3); component node21 = new leaf("21"); component node22 = new composite("22"); node2.add(node21); node2.add(node22); component node221 = new leaf("221"); node22.add(node221); root.print(); } } composite:root --left:1 --composite:2 ----left:21 ----composite:22 ------left:221 --left:3
jdk
- javax.swing.jcomponent#add(component)
- java.awt.container#add(component)
- java.util.map#putall(map)
- java.util.list#addall(collection)
- java.util.set#addall(collection)
4. 装饰(decorator)
intent
为对象动态添加功能。
class diagram
装饰者(decorator)和具体组件(concretecomponent)都继承自组件(component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。
implementation
设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。
下图表示在 darkroast 饮料上新增新添加 mocha 配料,之后又添加了 whip 配料。darkroast 被 mocha 包裹,mocha 又被 whip 包裹。它们都继承自相同父类,都有 cost() 方法,外层类的 cost() 方法调用了内层类的 cost() 方法。
public interface beverage { double cost(); } public class darkroast implements beverage { @override public double cost() { return 1; } } public class houseblend implements beverage { @override public double cost() { return 1; } } public abstract class condimentdecorator implements beverage { protected beverage beverage; } public class milk extends condimentdecorator { public milk(beverage beverage) { this.beverage = beverage; } @override public double cost() { return 1 + beverage.cost(); } } public class mocha extends condimentdecorator { public mocha(beverage beverage) { this.beverage = beverage; } @override public double cost() { return 1 + beverage.cost(); } } public class client { public static void main(string[] args) { beverage beverage = new houseblend(); beverage = new mocha(beverage); beverage = new milk(beverage); system.out.println(beverage.cost()); } } 3.0
设计原则
类应该对扩展开放,对修改关闭:也就是添加新功能时不需要修改代码。饮料可以动态添加新的配料,而不需要去修改饮料的代码。
不可能把所有的类设计成都满足这一原则,应当把该原则应用于最有可能发生改变的地方。
jdk
- java.io.bufferedinputstream(inputstream)
- java.io.datainputstream(inputstream)
- java.io.bufferedoutputstream(outputstream)
- java.util.zip.zipoutputstream(outputstream)
- java.util.collections#checkedlist|map|set|sortedset|sortedmap
5. 外观(facade)
intent
提供了一个统一的接口,用来访问子系统中的一群接口,从而让子系统更容易使用。
class diagram
implementation
观看电影需要操作很多电器,使用外观模式实现一键看电影功能。
public class subsystem { public void turnontv() { system.out.println("turnontv()"); } public void setcd(string cd) { system.out.println("setcd( " + cd + " )"); } public void startwatching(){ system.out.println("startwatching()"); } } public class facade { private subsystem subsystem = new subsystem(); public void watchmovie() { subsystem.turnontv(); subsystem.setcd("a movie"); subsystem.startwatching(); } } public class client { public static void main(string[] args) { facade facade = new facade(); facade.watchmovie(); } }
设计原则
最少知识原则:只和你的密友谈话。也就是说客户对象所需要交互的对象应当尽可能少。
6. 享元(flyweight)
intent
利用共享的方式来支持大量细粒度的对象,这些对象一部分内部状态是相同的。
class diagram
- flyweight:享元对象
- intrinsicstate:内部状态,享元对象共享内部状态
- extrinsicstate:外部状态,每个享元对象的外部状态不同
implementation
public interface flyweight { void dooperation(string extrinsicstate); } public class concreteflyweight implements flyweight { private string intrinsicstate; public concreteflyweight(string intrinsicstate) { this.intrinsicstate = intrinsicstate; } @override public void dooperation(string extrinsicstate) { system.out.println("object address: " + system.identityhashcode(this)); system.out.println("intrinsicstate: " + intrinsicstate); system.out.println("extrinsicstate: " + extrinsicstate); } } public class flyweightfactory { private hashmap<string, flyweight> flyweights = new hashmap<>(); flyweight getflyweight(string intrinsicstate) { if (!flyweights.containskey(intrinsicstate)) { flyweight flyweight = new concreteflyweight(intrinsicstate); flyweights.put(intrinsicstate, flyweight); } return flyweights.get(intrinsicstate); } } public class client { public static void main(string[] args) { flyweightfactory factory = new flyweightfactory(); flyweight flyweight1 = factory.getflyweight("aa"); flyweight flyweight2 = factory.getflyweight("aa"); flyweight1.dooperation("x"); flyweight2.dooperation("y"); } } object address: 1163157884 intrinsicstate: aa extrinsicstate: x object address: 1163157884 intrinsicstate: aa extrinsicstate: y
jdk
java 利用缓存来加速大量小对象的访问时间。
- java.lang.integer#valueof(int)
- java.lang.boolean#valueof(boolean)
- java.lang.byte#valueof(byte)
- java.lang.character#valueof(char)
7. 代理(proxy)
intent
控制对其它对象的访问。
class diagram
代理有以下四类:
- 远程代理(remote proxy):控制对远程对象(不同地址空间)的访问,它负责将请求及其参数进行编码,并向不同地址空间中的对象发送已经编码的请求。
- 虚拟代理(virtual proxy):根据需要创建开销很大的对象,它可以缓存实体的附加信息,以便延迟对它的访问,例如在网站加载一个很大图片时,不能马上完成,可以用虚拟代理缓存图片的大小信息,然后生成一张临时图片代替原始图片。
- 保护代理(protection proxy):按权限控制对象的访问,它负责检查调用者是否具有实现一个请求所必须的访问权限。
- 智能代理(smart reference):取代了简单的指针,它在访问对象时执行一些附加操作:记录对象的引用次数;当第一次引用一个对象时,将它装入内存;在访问一个实际对象前,检查是否已经锁定了它,以确保其它对象不能改变它。
implementation
以下是一个虚拟代理的实现,模拟了图片延迟加载的情况下使用与图片大小相等的临时内容去替换原始图片,直到图片加载完成才将图片显示出来。
public interface image { void showimage(); } public class highresolutionimage implements image { private url imageurl; private long starttime; private int height; private int width; public int getheight() { return height; } public int getwidth() { return width; } public highresolutionimage(url imageurl) { this.imageurl = imageurl; this.starttime = system.currenttimemillis(); this.width = 600; this.height = 600; } public boolean isload() { // 模拟图片加载,延迟 3s 加载完成 long endtime = system.currenttimemillis(); return endtime - starttime > 3000; } @override public void showimage() { system.out.println("real image: " + imageurl); } } public class imageproxy implements image { private highresolutionimage highresolutionimage; public imageproxy(highresolutionimage highresolutionimage) { this.highresolutionimage = highresolutionimage; } @override public void showimage() { while (!highresolutionimage.isload()) { try { system.out.println("temp image: " + highresolutionimage.getwidth() + " " + highresolutionimage.getheight()); thread.sleep(100); } catch (interruptedexception e) { e.printstacktrace(); } } highresolutionimage.showimage(); } } public class imageviewer { public static void main(string[] args) throws exception { string image = "http://image.jpg"; url url = new url(image); highresolutionimage highresolutionimage = new highresolutionimage(url); imageproxy imageproxy = new imageproxy(highresolutionimage); imageproxy.showimage(); } }
jdk
- java.lang.reflect.proxy
- rmi