适配器模式
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。
示例演示:
由于我们之前的例子都是围绕people和animal来的,所以我们依然用people来举例,例子可能不太恰当,网上有更好的例子;这次我们把people设计成一个接口,这个接口提供了一个eat的方法,方法有两个参数,什么类型的食物,和食物名称
1
2
3
4
5package test.adapter;
public interface People {
public void eat(String type, String name);
}这时候我们新增两个接口,一个吃荤,一个吃素
1
2
3
4
5
6
7package test.adapter;
public interface AdvancedPeople {
public void eatMeat(String name);
public void eatVege(String name);
}然后我们创建两个实体类,分别来实现这俩方法
1
2
3
4
5
6
7
8
9
10
11
12
13package test.adapter;
public class PeopleEatMeat implements AdvancedPeople{
public void eatMeat(String name) {
System.out.println("eat meat :"+name);
}
public void eatVege(String name) {
}
}1
2
3
4
5
6
7
8
9
10
11
12
13package test.adapter;
public class PeopleEatVege implements AdvancedPeople{
public void eatMeat(String name) {
}
public void eatVege(String name) {
System.out.println("eat vege :"+name);
}
}接下来重点来了,我们创建一个适配eat的适配器实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package test.adapter;
public class PeopleAdapter implements People {
AdvancedPeople advancedPeople;
public PeopleAdapter(String type) {
if (type.equalsIgnoreCase("meat")) {
advancedPeople = new PeopleEatMeat();
} else if (type.equalsIgnoreCase("vege")) {
advancedPeople = new PeopleEatVege();
}
}
public void eat(String type, String name) {
if (type.equalsIgnoreCase("meat")) {
advancedPeople.eatMeat(name);
} else if (type.equalsIgnoreCase("vege")) {
advancedPeople.eatVege(name);
}
}
}创建一个people接口实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package test.adapter;
public class PeopleImpl implements People {
PeopleAdapter peopleAdapter;
public void eat(String type, String name) {
if (type.equalsIgnoreCase("food")) {
System.out.println("eat food :"+name);
}else if (type.equalsIgnoreCase("meat") || type.equalsIgnoreCase("vege")){
peopleAdapter = new PeopleAdapter(type);
peopleAdapter.eat(type,name);
}else if (type.equalsIgnoreCase("fruit")){
System.out.println(name+" not supported");
}
}
}完成上述步骤,我们就可以开始演示了
1
2
3
4
5
6
7
8
9
10
11package test.adapter;
public class AdapterDemo {
public static void main(String[] args) {
PeopleImpl people = new PeopleImpl();
people.eat("food","rice");
people.eat("meat","fish");
people.eat("vege","tomato");
people.eat("fruit","apple");
}
}运行结果:
1
2
3
4eat food :rice
eat meat :fish
eat vege :tomato
apple not supported
说明:
优点: 1、可以让任何两个没有关联的类一起运行。 2、提高了类的复用。 3、增加了类的透明度。 4、灵活性好。
缺点: 1、过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。 2.由于 JAVA 至多继承一个类,所以至多只能适配一个适配者类,而且目标类必须是抽象类。