“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.” ---GoF
将一个类的接口转化为客户期望的另外一个接口。适配器模式使得原本拥有不兼容接口的类能一起“工作”。--GoF
Adapter Pattern 是一种比较简单的模式。模式中需要适配的接口(即 Adaptee),既可以被适配器继承,也可以被适配器通过组合的方式使用。前者称为类适配模式,后者用组合的方式称为对象适配模式。
当需要用到某个类的一些方法,但是这个类又不能完全满足要求,此时,你不能修改这个类的代码,就要考虑用适配器模式。
类的适配器模式:
对象适配器模式:
相关代码比较简单,可以直接浏览这里参考:
参考: