设计模式-适配器模式

适配器模式

定义:将一个类的接口转换为用户希望的另一个接口。这使得原本由于接口不兼容而不能一起工作的那些类就可以一起工作了

接下来我们来模拟USB转接网线口,从而使电脑上网的案例

网线接口

1
2
3
public interface NetWorkThread {
void connectNetWork();
}

华为的网线

1
2
3
4
5
6
public class HuaWeiNetWorkThread implements NetWorkThread{
@Override
public void connectNetWork() {
System.out.println("华为网线连接网络,可以上网了");
}
}

自制的网线

1
2
3
4
5
6
public class CustomerNetWorkThread implements NetWorkThread{
@Override
public void connectNetWork() {
System.out.println("自制网线,可以上网了");
}
}

适配器(网线口变为USB口)

1
2
3
public interface Adapter {
void netWorkToUSB();
}

华为的适配器(转接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HuaWeiAdapter implements Adapter{
private NetWorkThread netWorkThread;

public void setNetWorkThread(NetWorkThread netWorkThread) {
this.netWorkThread = netWorkThread;
}

@Override
public void netWorkToUSB() {
if(netWorkThread==null){
System.out.println("适配器没有网线插入!");
return;
}
System.out.println("华为适配器适配了网线");
netWorkThread.connectNetWork();
}
}

电脑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Computer {
private Adapter adapter;

public void setAdapter(Adapter adapter) {
this.adapter = adapter;
}

public void connectToNetWork(){
if(adapter!=null){
adapter.netWorkToUSB();
}else {
System.out.println("没有插网线!");
}
}
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
computer.connectToNetWork();
System.out.println("===================");
HuaWeiAdapter huaWeiAdapter = new HuaWeiAdapter();
computer.setAdapter(huaWeiAdapter);
computer.connectToNetWork();
System.out.println("===================");
huaWeiAdapter.setNetWorkThread(new HuaWeiNetWorkThread());
computer.connectToNetWork();
}
}

控制台输出

1
2
3
4
5
6
没有插网线!
===================
适配器没有网线插入!
===================
华为适配器适配了网线
华为网线连接网络,可以上网了
给作者买杯咖啡吧~~~