[译]Java 设计模式之适配器
(文章翻译自Java Design Pattern: Adapter)
适配器模式在现在的Java框架中被频繁的用到。
当你想去使用一个存在的类而且它的接口和你需要的不吻合,或者是你想去创建一个可复用的类但是这个需要和一个没有关系的类和不兼容的接口协作的时候,那么就可以用到适配器模式了。
1.适配器的来历
适配器是思想可以通过下面的简单例子来演示。下面例子的目的就是使一个橘子能够适配一个苹果。
在图的下部分,适配器有一个Orange实例,而且是继承自苹果的。它看起来一个橘子对象获取了一个适配器的皮肤,但是它可以看起来像是一个苹果对象。
2.适配器类图
3.适配器模式Java代码
Adapter pattern is frequently used in modern Java frameworks.
It comes into place when you want to use an existing class, and its interface does not match the one you need, or you want to create a reusable class that cooperates with unrelated classes with incompatible interfaces.
1. Adapter pattern story
The Adapter idea can be demonstrated with the following simple example. The purpose of the sample problem is to adapt an orange as an apple.
Java Adapter Design Pattern
From the lower diagram, the adapter contains an instance of Orange, and extends Apple. It seems to be that after an Orange object gets a adapter skin, it acts like an Apple object now.
2. Adapter class diagram
adapter-pattern-class-diagram
3. Adapter pattern Java code
class Apple {
public void getAColor(String str) {
System.out.println("Apple color is: " + str);
}
}
class Orange {
public void getOColor(String str) {
System.out.println("Orange color is: " + str);
}
}
class AppleAdapter extends Apple {
private Orange orange;
public AppleAdapter(Orange orange) {
this.orange = orange;
}
public void getAColor(String str) {
orange.getOColor(str);
}
}
public class TestAdapter {
public static void main(String[] args) {
Apple apple1 = new Apple();
Apple apple2 = new Apple();
apple1.getAColor("green");
Orange orange = new Orange();
AppleAdapter aa = new AppleAdapter(orange);
aa.getAColor("red");
}
}
4.在Java标准开发包中使用适配器模式
java.io.InputStreamReader(InputStream) (返回 a Reader)
java.io.OutputStreamWriter(OutputStream) (返回 a Writer)
在实际更大的框架中,这个应用可能不会这么明显。例如适配器的思想在Eclipse中的使用不是那么容易发现的。