概念
配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。
适配器模式是将某个类的接口转换成客户端期望的另一个接口表示,使原本由于接口不兼容而不能一起工作的那些类可以一起工作。或者使一个类兼容一个接口。
优点:
- 可以让任何两个没有关联的类在同一个环境(接口)下工作。
- 提高了类的复用(不用总写重复代码)。
缺点:
- 过多地使用适配器,会让系统非常零乱,不易把握整体。造成对一些用户的不透明。比如,明明看到调用的是 A 接口方法,其实内部被适配成了 B 接口的实现,即实际内部是调用了B接口的方法。
- 由于 JAVA 至多继承一个类,所以类的适配器模式至多只能适配一个适配者类,而且目标必须是接口或抽象类。
类的适配器模式
想在新环境中使用已有类–(多)继承实现。
//被适配的接口
interface Adaptee{
void SpecificRequest();
}
//实现被适配接口的类
class SpecificAdaptee implements Adaptee{
@Override
public void SpecificRequest() {
System.out.println("SpecificAdaptee类的SpecificRequest()");
}
}
//实际环境需要的接口
interface Target {
void Request();
}
//适配器
class Adapter extends SpecificAdaptee implements Target{
@Override
public void Request() {
System.out.println("Target接口的Request()");
SpecificRequest();
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Target target = new Adapter();
target.Request();
}
}
Output:
Target接口的Request()
SpecificAdaptee类的SpecificRequest()
对象的适配器模式
想使用某个类的许多子类的方法–组合实现。
//被适配的接口
interface Adaptee{
void SpecificRequest();
}
//实现被适配接口的类
class SpecificAdaptee implements Adaptee{
@Override
public void SpecificRequest() {
System.out.println("SpecificAdaptee类的SpecificRequest()");
}
}
//实际环境需要的接口
interface Target {
void Request();
}
//适配器
class Wrapper implements Target {
private Adaptee adaptee;
public Wrapper(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void Request() {
System.out.println("Target接口的Request()");
adaptee.SpecificRequest();
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Target target = new Wrapper(new SpecificAdaptee());
target.Request();
}
}
Output:
Target接口的Request()
SpecificAdaptee类的SpecificRequest()
接口的适配器模式
一个接口中有多个抽象方法,若想实现该接口则必须实现该接口的所有方法,这比较浪费,因为并不是接口中所有的方法都是我们需要的,有时只需要其中的一部分。
创建一个实现了该接口(所有方法)的抽象类。我们不和原始的接口打交道,只和该抽象类取得联系。当我们的类需要接口中的部分方法时,就写一个类,继承该抽象类,并重写我们需要的方法就行了。
要用的接口:
package adapter;
public interface TargetInterface {
void method1();
void method2();
void method3();
}
实现了该接口(所有方法)的抽象类:
package adapter;
public abstract class AbstractAdapter implements TargetInterface{
public void method1() {
System.out.println("TargetInterface method1");
}
public void method2() {
System.out.println("TargetInterface method2");
}
public void method3() {
System.out.println("TargetInterface method3");
}
}
只用到接口中部分方法的类:只需要重写我们用到的接口方法,无需每次重写所有接口方法
package adapter;
public class ImplementClass extends AbstractAdapter{
public void method1() {
System.out.println("ImplementClass method1");
}
public void method3() {
System.out.println("ImplementClass method3");
}
}
客户端:
package adapter;
public class AdapterTest {
public static void main(String[] args) {
TargetInterface target = new ImplementClass();
target.method1();
target.method2();
target.method3();
}
}
Output:
ImplementClass method1
TargetInterface method2
ImplementClass method3