1. 含义
把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作.
2. 类图
类适配
对象适配
3. 类代码
类适配
/**
* 目标角色,期望得到的接口
*/
public interface Target {
/**
* 这是源类也有的方法
*/
void sampleOperation1();
/**
* 这是源类没有的方法
*/
void sampleOperation2();
}
/**
* 源角色,需要适配的接口
*/
public class Adaptee {
//源类含有的方法
public void sampleOperation1() {
};
}
/*
* 适配器角色,把源接口转换成目标接口
*/
public class Adapter extends Adaptee implements Target {
/**
* 由于源类没有这个方法,因此适配器类补充上这个方法
*/
public void sampleOperation2() {
}
}
/*
* 测试类
*/
public class Test {
public static void main(String[] args) {
Adapter a = new Adapter();
a.sampleOperation1();
a.sampleOperation2();
}
}
对象适配
/*
* 适配器角色,把源接口转换成目标接口
*/
public class Adapter implements Target {
//把源类作为一个属性
private Adaptee adaptee ;
public Adapter(Adaptee adaptee) {
super();
this.adaptee = adaptee;
}
/**
* 源类有该方法,所有适配器类直接委派即可
*/
public void sampleOperation1() {
adaptee.sampleOperation1();
}
public void sampleOperation2() {
}
}
/*
* 测试类
*/
public class Test {
public static void main(String[] args) {
Adapter a = new Adapter(new Adaptee());
a.sampleOperation1();
a.sampleOperation2();
}
}
z