23种设计模式(适配器模式)
(愿岁月清净)
一、对适配器模式的理解
类似于电脑上网需要用usb接口插网线,但是网线不是usb接口,所以需要一个适配器把两个连接起来。
二、直接上代码
Adaptee
package com.kuang.adapter;
//要被适配的类:网线
public class Adaptee {
public void request() {
System.out.println("连接网线上网");
}
}
Adapter
package com.kuang.adapter;
//真正的适配器,需 要连接USB,连接网线~
public class Adapter extends Adaptee implements NetToUsb {
@Override
public void handleRequest() {
//上网的具体实现,找一个转接头
super.request();
}
}
NetToUsb
package com.kuang.adapter;
//按1口转换器的抽象实现~
public interface NetToUsb {
//作1川:处理请求,网线=>usb
public void handleRequest();
}
Adapter2(组合)
package com.kuang.adapter;
//真正的适配器,需 要连接USB,连接网线~
public class Adapter2 implements NetToUsb {
//组合模式
private Adaptee adaptee;
public Adapter2(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void handleRequest() {
//上网的具体实现,找一个转接头
adaptee.request();//可以上网
}
}
Computer
package com.kuang.adapter;
//客户端关: 想上:网,插不L:网线~
public class Computer {
//我们的电脑需要连接1:转按器才可以1:网
public void net(NetToUsb adapter) {
//.上网的具体实现, 找“个转接义
adapter.handleRequest();
}
public static void main(String[] args) {
/* //电脑,适配器,网线~
Computer computer = new Computer(); //电脑
Adaptee adaptee = new Adaptee(); //网线
Adapter adapter = new Adapter(); //转按器
computer.net(adapter);*/
System.out.println("++++++++++++++++++++++++++++++");
//电脑,适配器,网线~
Computer computer = new Computer(); //电脑
Adaptee adaptee = new Adaptee(); //网线
Adapter2 adapter = new Adapter2(adaptee); //转按器
computer.net(adapter);
}
}