Java设计模式——适配器模式(Adapter Pattern)

适配器模式:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式UML类图如下:

Java设计模式——适配器模式(Adapter Pattern)

从UML类图可以看出,适配器模式包含3个元素:

目标角色(Target):客户所期待得到的接口。

源角色(Adaptee):需要适配的类。

适配器角色(Adapter):​​​​​​​通过包装一个需要适配的对象,把原接口转换成目标接口。

具体代码:

1.目标角色类

package com.szcatic.adapter;

public interface Target {
	
	void demand();
}

2.源角色类

package com.szcatic.adapter;

public class Adaptee {
	
	public void specialRequirements() {
		System.out.println("特殊要求");
	}
}

3.适配器角色类

package com.szcatic.adapter;

public class Adapter implements Target {
	
	private Adaptee adaptee;

	public Adapter(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	@Override
	public void demand() {
		adaptee.specialRequirements();
	}
	
}

4.测试类

package com.szcatic.adapter.test;

import org.junit.jupiter.api.Test;

import com.szcatic.adapter.Adaptee;
import com.szcatic.adapter.Adapter;

public class AdapterTest {
	
	@Test
	void testDemand() {
		new Adapter(new Adaptee()).demand();
	}
}

5.运行结果

特殊要求

总结

优点:

1、可以让任何两个没有关联的类一起运行。

2、提高了类的复用。

3、增加了类的透明度。

4、灵活性好。

缺点: 

 1、过多地使用适配器,会让系统非常零乱,不易整体进行把握。