适配器模式 形象来说就是转接头模式, 是为了兼容标准不统一的接口 的模式;
接口 A 和 接口b 对不上,这个时候我们要写一个接口c来 使他们连接起来;
不多说 直接上代码:
1, 继承和实现接口
// 电脑
package adapter;
public interface Target {
void handleRes();
}
package adapter;
public class Computer {
public void test(Target t) {
t.handleRes();
}
}
// 转换头
package adapter;
public class Adapter extends Keyboard implements Target{
@Override
public void handleRes() {
super.handleReq();
}
}
// 键盘
package adapter;
public interface Target1 {
void handleReq();
}
package adapter;
public class Keyboard implements Target1 {
@Override
public void handleReq() {
System.out.println("键盘输出了一句话");
}
}
// 客户端
package adapter;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Computer computer = new Computer();
computer.test(new Adapter());
}
}
2,属性和实现接口( 这种才是我们想要的 ,扩展性都很好) 在以上代码替换转接口和客户端代码
// 1,转接头
package adapter;
public class Adapter extends Keyboard implements Target{
private Keyboard Keyboard;
public Adapter(adapter.Keyboard keyboard) {
super();
Keyboard = keyboard;
}
@Override
public void handleRes() {
this.Keyboard.handleReq();
}
}
// 2, 客户端
package adapter;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Computer computer = new Computer();
computer.test(new Adapter(new Keyboard()));
}
}