适配器模式简介

  • 适配器模式是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
  • 这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。

类模式

要被适配的类TV和类Wire
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//要被适配的类:电视
public class TV {
//电视剧需要一个电源适配器,就可以供电,开机
public void open(IPowerAdapter iPowerAdapter) {
//打开电视,需要电,需要连接电线,需要一个电源适配器
iPowerAdapter.power();
}
}

//要被适配接入的类:电线
public class Wire {
public void supply() {
System.out.println("供上电了...");
}
}
电源适配器接口IPowerAdapter
1
2
3
4
5
//电源适配器接口
public interface IPowerAdapter {
//供电
void power();
}
电线和电视机适配器类TVPowerAdapter(通过继承方式)
1
2
3
4
5
6
7
//真正的适配器,一端连接电线,一端连接电视
public class TVPowerAdapter extends Wire implements IPowerAdapter {
@Override
public void power() {
super.supply();//有电了
}
}
测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Test {
public static void main(String[] args) {
TV tv = new TV();//电视
TVPowerAdapter tvPowerAdapter = new TVPowerAdapter();//电源适配器
Wire wire = new Wire();//电线

tv.open(tvPowerAdapter);

/**
* 输出结果:
* 供上电了...
*/
}
}
测试结果
1
供上电了...

组合模式(推荐使用)

要被适配的类TV和类Wire
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//要被适配的类:电视
public class TV {
//电视剧需要一个电源适配器,就可以供电,开机
public void open(IPowerAdapter iPowerAdapter) {
//打开电视,需要电,需要连接电线,需要一个电源适配器
iPowerAdapter.power();
}
}

//要被适配接入的类:电线
public class Wire {
public void supply() {
System.out.println("供上电了...");
}
}
电源适配器接口IPowerAdapter
1
2
3
4
5
//电源适配器接口
public interface IPowerAdapter {
//供电
void power();
}
电线和电视机适配器类TVPowerAdapter(通过组合方式)
1
2
3
4
5
6
7
8
9
10
11
12
13
//真正的适配器,一端连接电线,一端连接电视
public class TVPowerAdapter implements IPowerAdapter {
private Wire wire;

public TVPowerAdapter(Wire wire) {
this.wire = wire;
}

@Override
public void power() {
wire.supply();//有电了
}
}
测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Test {
public static void main(String[] args) {
TV tv = new TV();//电视
Wire wire = new Wire();//电线
TVPowerAdapter tvPowerAdapter = new TVPowerAdapter(wire);//电源适配器

tv.open(tvPowerAdapter);

/**
* 输出结果:
* 供上电了...
*/
}
}
测试结果
1
供上电了...