适配器adapter模式
将一个类的接口转化成客户说需要的接口,可以使由于接口不兼容不能在一起工作而变得可以在一起工作
模式中的角色:
- 目标接口(Target)客户期待的接口,可以是接口,具体或抽象的类
- 需要适配的类:(Adaptee)
- 适配器(Adapter)通过包装一个需要适配的对象,把原接口转化成目标接口
Adaptee.java
/**
* adapee
* 键盘的ps2接口
* @author Administrator
*
*/
public class KeyBoard {
public void req() {
System.out.println("打字功能");
}
}
Target.java
/**
* 目标接口
* @author Administrator
*
*/
public interface Target {
void handlerReq();
}
Adapter.Java
/**
* 对象适配器
* 相当于ps2/usb适配器
* @author Administrator
*
*/
public class Adapter implements Target {
private KeyBoard kb;
public Adapter(KeyBoard kb) {
this.kb = kb;
}
@Override
public void handlerReq() {
kb.req();
}
}
/**
* 电脑,只有usb接口,要借助适配器调用键盘
* @author Administrator
*
*/
public class Computer {
public void test(Target t) {
t.handlerReq();
}
public static void main(String[] args) {
Computer c=new Computer();
c.test(new Adapter(new KeyBoard()));//方式一
c.test(new Adapter2());//方式二
}
}