定义
将一个类的接口转换成客户希望的另外一个接口,从而使两个原本因为不匹配而无法在一起工作的两个类能够在一起工作
适配器模式中的角色
1:目标(Target)角色:这就是所期待得到的接口。
public interface Target{ public void request();}
(2)源(Adaptee)角色:现在需要适配的接口。
public class Adaptee{ public void specificRequest(){}}
(3)适配器(Adapter)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。
public class Adapter extends Adaptee implements Target{ public void request(){ super.specificRequest(); }}
调用示例
public void Client{ public static void main(String [] args) { Target target = new Adapter(); target.request(); }}
优点
增加了类的透明性
提高了类的复用性
增强代码的灵活性
使用场景
修改一个已经投产中的系统时,对系统中不符合系统接口的类,转换成符合系统接口的类
参考资料:设计模式(java)
文章转载于:https://www.jianshu.com/p/3bccc68ac72c
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~