设计模式之适配器模式(Adapter Pattern)

  • 适配器模式定义
    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. 将一个类的接口变换成客户端所期待的另一种接口,从而是原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
  • 适配器模式通用类图
    设计模式之适配器模式(Adapter Pattern)
    适配器模式主要有三个角色:
    • Target目标角色:该角色定义把其他类型转换为何种接口,也就是我们期望的接口。
    • Adapter适配器角色:通过包装一个需要适配的对象,把原接口转换成目标接口,主要通过继承或者类关联的方法实现。
    • Adaptee源角色:你想把某个对象转换成目标角色,这个对象就是源角色。源角色是已经存在的、运行良好的类或者对象,经过适配器角色的包装,就会成为一个新的对象。一句话来说就是需要适配的类或适配者类。
  • 适配器模式通用代码
    目标角色
public interface Target {

	void request();
}

目标角色的实现类

public class ConcreteTarget implements Target{

	@Override
	public void request() {
		System.out.println("this is ConcreteTarget");
	}
}

源角色

public class Adaptee {

	public void doSth() {
		System.out.println("this is Adaptee");
	}
}

适配器角色

public class Adapter extends Adaptee implements Target{

	@Override
	public void request() {
		
		super.doSth();
	}
}

调用类

public class Client {

	public static void main(String[] args) {
		
		Target target = new ConcreteTarget();
		target.request();
		Target target1 = new Adapter();
		target1.request();
	}
}
  • 适配器模式实例
    暂时想不到什么比较生动的例子,看过别人的文章都在用生活中充电器的例子。实例参考,在此感谢分享。
  • 适配器模式优点
    • 复用了现存的类,解决了现存类和复用环境要求不一致的问题。
    • 将目标类和适配者类解耦,通过引入一个适配器类重用现有的适配者类,而无需修改原有代码。

参考书籍:设计模式之禅
实例代码放在这里