把不同的接口通过中间的adapter 连接在一起,概念很简单,看玩具代码很简单。
Example in JDK:
java.util.Array #asList()
java.io.InputStreamReader(InputStream)(returns a Reader)
java.io.OutputStreamWriter(OutputStream)(returns a Writer)
-
package adapterpattern;
-
-
class Apple{
-
public void getAppleColor(String color){
-
System.out.println("Apple color is :"+color);
-
}
-
}
-
-
class Orange{
-
public void getOrangeColor(String color){
-
System.out.println("Orange color is :"+color);
-
}
-
}
-
-
class AppleAdapter extends Apple{
-
-
//The purpose of the sample problme is to adapt an orange
-
// as an apple
-
private Orange orange;
-
-
public AppleAdapter(Orange orange){
-
this.orange = orange;
-
}
-
-
public void getColor(String color){
-
orange.getOrangeColor(color);
-
}
-
}
-
-
-
public class AdapterPatternDemo {
-
public static void main(String[] args){
-
Apple apple1 = new Apple();
-
apple1.getAppleColor("green");
-
-
Orange orange = new Orange();
-
AppleAdapter adapter = new AppleAdapter(orange);
-
adapter.getAppleColor("red");
-
}
-
}
阅读(574) | 评论(0) | 转发(0) |