package com.bjsxt.adapter;
/**
* 被适配的类
* (相当于例子中的,PS/2键盘)
* @author Administrator
*
*/
public class Adaptee {
public void request(){
System.out.println("可以完成客户请求的需要的功能!");
}
}
package com.bjsxt.adapter;
/**
*目标接口
* (相当于例子中的,USB接口)
* @author Administrator
*
*/
public interface Target {
void handleReq();
}
package com.bjsxt.adapter;
/**
* 适配器 (类适配器方式)
* (相当于usb和ps/2的转接器)
* @author Administrator
*
*/
public class Adapter extends Adaptee implements Target {
@Override
public void handleReq() {
super.request();
}
}
package com.bjsxt.adapter;
/**
* 适配器 (对象适配器方式,使用了组合的方式跟被适配对象整合)
* (相当于usb和ps/2的转接器)
* @author Administrator
*
*/
public class Adapter2 implements Target {
private Adaptee adaptee;
@Override
public void handleReq() {
adaptee.request();
}
public Adapter2(Adaptee adaptee) {
super();
this.adaptee = adaptee;
}
}
package com.bjsxt.adapter;
/**
* 客户端类
* (相当于例子中的笔记本,只有USB接口)
* @author Administrator
*
*/
public class Client {
public void test1(Target t){ //只和USB接口进行交互
t.handleReq();
}
public static void main(String[] args) {
Client c = new Client();
Adaptee a = new Adaptee();
// Target t = new Adapter();
Target t = new Adapter2(a);
c.test1(t); //适配器实现了目标接口,把适配器传进来,适配器又继承了父类被适配类的方法,使得用户和被适配的类进行了交互!
}
}