1. 类图
- Target:客户端需要的功能接口
- Adaptee:需要被适配的接口
- Adapter:适配器,将Adaptee适配成客户端需要的Target
- Client:客户端,调用功能接口Target
2. 示例
2.1 默认适配器
减少子类重写的方法
2.1.1 接口
// 默认适配接口
public interface DefaultAdapter {
public void testOne();
public void testTwo();
public void testThree();
}
2.1.2 默认实现
public class DefaultAdapterImpl implements DefaultAdapter {
public void testOne() {}
public void testTwo() {}
public void testThree() {}
}
2.1.3 目标类
public class Target extends DefaultAdapterImpl {
@Override
public void testTwo() {System.out.println("我只需要重写testTwo方法");}
}
2.2 对象适配器
外表为新对象,内部为存在的旧对象
2.2.1 现存的对象
public class Dog {
public void say(){System.out.println("汪汪汪");}
}
2.2.2 新对象接口
public interface Target {
void say();
}
2.2.3 新的对象接口实现
public class Cat implements Target {
private Dog dog;
public Cat(Dog dog){this.dog = dog;}
public void say() {
dog.say();
}
}
2.2.4 客户端
public class Client {
public static void main(String[] args) {
// 创建现存的对象
Dog dog = new Dog();
// 传入现存对象,创建新的对象
Target target = new Cat(dog);
// 调用新的功能
target.say();
}
}
2.3 类适配器
新的类有自己的功能,也有现有的功能
2.3.1 现有的功能
public class Adapteeobj {
public void run(){System.out.println("我会跑");}
public void sleep(){System.out.println("我会睡");}
}
2.3.2 需要扩展的功能
public interface AdapteeInter {
void eat();
}
2.3.3 新的类
public class Adapter extends Adapteeobj implements AdapteeInter {
public void eat() {System.out.println("我会吃");}
}
2.3.4 客户端
public class Client {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.eat();
adapter.run();
adapter.sleep();
}
}
3. 优点
- 更好的复用性
- 复用已经存在的功能来满足客户新的功能
- 更好的可扩展性
- 实现适配器功能时,可以调用自己开发的功能
4. 缺点
- 过多的使用适配器模式,会让系统非常凌乱,不容易整体把握
- 外部调用的是A接口,内部却是使用B接口来实现功能