设计模式之适配器模式

Java62

本文通过老王使用纸质书籍阅读小王使用电子书籍的故事,详细说明设计模式中的结构型设计模式之适配器模式,分别对对象适配器和类适配器代码实现,最后为了加深理解,会列举适配器设计模式在JDK和Spring源码中的应用。

一、引出问题

自从小王被老王赶出家门后,老王就舒舒服服地住了几天,家里的书架上也买了不少纸质书。

[En]

Since Xiao Wang was driven out of the house by Lao Wang, Lao Wang has lived comfortably for a few days and bought a lot of paper books on the bookshelf at home.

一天,小王过着野蛮的生活回来了。小王也是个喜欢读书的人,但小王不喜欢纸质书,就让老王换成电子书。

[En]

One day, Xiao Wang came back from living a savage life. Xiao Wang is also a person who likes reading, but Xiao Wang doesn't like paper books, so he asks Lao Wang to replace them with electronic ones.

老王马上就不高兴了。我不知道设计这个书架花了多少个昼夜。用电子版取代它,不仅要花费我大量的精力来改变原有书架的结构,而且要找到我想读的书有多难。如果老李来了,想看纸质版,我是不是要改回去?

[En]

Lao Wang was unhappy immediately. I don't know how many days and nights it took to design the bookshelf. Replacing it with an electronic version will not only cost me a lot of energy to change the structure of the original bookshelf, but also how difficult it is to find the book I want to read. and what if Lao Li comes and wants to see the paper version, do I have to change it back?

老王满意地点了点头,你说得对,这其实就是结构设计模式中的适配器模式。

[En]

Lao Wang nodded with satisfaction, you are right, this is actually the adapter pattern in the structural design pattern.

二、概念与使用

引用Gof中对适配器设计模式的概念:将一个类的接口转化成客户希望的另一个接口,由于接口不兼容而不能一起工作的类可以一起工作。

很显然,在适配器设计模式中应该有三个角色。

目标类:Target,该角色把其他类转换为我们期望的接口,可以是一个抽象类或接口,也可以是具体类。
被适配者类(源): Adaptee ,原有的接口,也是希望被适配的接口。

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长