天天看点

结构型设计模式(1):适配器模式

定义 适配器模式(英语:adapter pattern)有时候也称包装样式或者包装。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起。

有两类适配器模式: 1. 对象适配器模式 - 对象适配器通过关联满足用户期待接口,还降低了代码间的不良耦合。在工作中推荐使用“对象适配”。 2. 类适配器模式 - 这种适配器模式下,适配器继承自已实现的类(一般多重继承),java中没有多重继承,所以这里不做介绍。

实现

结构型设计模式(1):适配器模式

1. Target - 定义Client需要使用的方法。 2. Adapter - 继承或者实现Target,适配Adaptee的方法到Target。 3. Adaptee - 定义一个已经存在的方法。 4. Client - 调用Target中的方法。

public class Adaptee {
	public void specificRequest(){
		System.out.println("Hello, I am from Adaptee!");
	}
}

public interface Target {
	public void request();
}

public class Adapter implements Target {
	Adaptee adaptee;
	public Adapter(){
		adaptee = new Adaptee();
	}
	public void request(){
		adaptee.specificRequest();
	}
}

public class Client {
	public static void main(String[] args) {
		Target target = new Adapter();
		target.request();
	}
}
           

要实现类适配器模式,我们需要Adapter继承Adaptee。

适用场景 1. 你想使用一个旧类,而它的接口不符合你的需求,那么可以使用Adapter类来作为中介类。 2. 你想创建一个可以通用的类,该类可以调用一些不相关的类的接口来供你使用。

参考 http://www.oodesign.com/adapter-pattern.html https://zh.wikipedia.org/wiki/%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F