一、什么是适配器模式?
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
/**
*被适配的类
* (相当于例子中的,PS/2键盘)
*/
public class Adaptee {
public void request(){
System.out.println("可以完成客户需要的功能!");
}
}
public interface Target {
void HandleReq();
}
/**
* 适配器(类适配器方式)
* (相当于usb和ps/2的转接器)
*/
public class Adapter extends Adaptee implements Target{
@Override
public void HandleReq() {
super.request();
}
}
/**
* 客户端类
* (相当于例子中的笔记本,只有USB接口)
*/
public class Client {
public void test1(Target t){
t.HandleReq();
}
public static void main(String[] args) {
Client c = new Client();
Adaptee a = new Adaptee();
Target t = new Adapter();
c.test1(t);
}
}
还有一种方式:
对象适配器模式,因为java只支持单继承,如果使用了继承的话,扩展不容易。使用组合的方式可能会更好。
public class Adapter2 implements Target {
private Adaptee adaptee;
@Override
public void HandleReq() {
adaptee.request();
}
public Adapter2(Adaptee adaptee) {
this.adaptee = adaptee;
}
}
/**
* 客户端类
* (相当于例子中的笔记本,只有USB接口)
*/
public class Client {
public void test1(Target t){
t.HandleReq();
}
public static void main(String[] args) {
Client c = new Client();
Adaptee a = new Adaptee();
// Target t = new Adapter();
// c.test1(t);
Target adapter2 = new Adapter2(a);
c.test1(adapter2);
}
}