Java Design Pattern: Adapter

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");
	}
 
}

Indeed, this probably is the simplest idea about adapter pattern. A double-way adapter may be used more often. To make a double-channel adapter, adapter requires to implements two interfaces and contains the two instances. It is still a simple idea.

4. Adapter Pattern used in Java SDK

java.io.InputStreamReader(InputStream) (returns a Reader)
java.io.OutputStreamWriter(OutputStream) (returns a Writer)

In a real large framework, the idea may not be very apparent. E.g. How the Adapter idea is used in Eclipse is not so easy to discover. This is a post towards how it is used in Eclipse Runtime.


转载于:https://my.oschina.net/u/148367/blog/173471

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值