设配器模式分为 类适配器模式 对象适配器模式,主要目的是 将适配者 与目标接口结合
类适配器模式: 目标接口 适配者 适配器
缺点:耦合度高
对象适配器:对类适配器 进行修改 继承改为聚合 关系 降低耦合度
package com.qf.adapterdemo.objectadapter;
//目标接口
public interface Target {
//目标业务
void request();
}
package com.qf.adapterdemo.objectadapter;
//适配者 就是 被转换类
public class Adapter {
public void specificRequest() {
System.out.println("适配者中的方法");
}
}
package com.qf.adapterdemo.objectadapter;
//对象适配器 取消继承 适配者 采用聚合
public class ObjectAdapter implements Target {
private Adapter adapter;
@Override
public void request() {
//适配者内的方法
adapter.specificRequest();
}
public ObjectAdapter(Adapter adapter) {
this.adapter = adapter;
}
}
package com.qf.adapterdemo.objectadapter;
public class ObjectAdapterTest {
public static void main(String[] args) {
System.out.println("对象设配器模式测试");
//多态 实际执行的是 配置器内的方法 配置器内 重写的方法 引入 适配者方法
Target target = new ObjectAdapter(new Adapter());
target.request();
}
}
总结:适配者 通过第三类(适配器 去转换)使原本不兼容的接口 兼容 提高复用性



