适配器分为两种,一种是对象适配器,另一种是类适配器,由于对象适配器使用的是组合,而类适配器使用的是继承的方式来实现两个类之间的转换的。所以根据设计模式的代码设计原则,这里只说下对象适配器,需要的元素如下:
1.目标(Target):客户所期待的接口,目标可以使具体的或者抽象的类,也可以是接口。
2.适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
3.被适配者(Adaptee).
UML图如下:
代码如下:
public interface Target {
/**
* 这是源类Adaptee也有的方法
*/
public void sampleOperation1();
/**
* 这是源类Adapteee没有的方法
*/
public void sampleOperation2();
}
public class Adaptee {
public void sampleOperation1(){}
}
public class Adapter {
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
/**
* 源类Adaptee有方法sampleOperation1
* 因此适配器类直接委派即可
*/
public void sampleOperation1(){
this.adaptee.sampleOperation1();
}
/**
* 源类Adaptee没有方法sampleOperation2
* 因此由适配器类需要补充此方法
*/
public void sampleOperation2(){
throw unSupportedOperationException();
}
}