适配器设计模型 适配器设计模式是怎么在Eclipse中使用?Eclipse平台Runtime有一个很好的例子。 首先,适配器设计模式的背后有一个简单的意图——封装一个对象,让他适用于客服端的其他接口,你可以在我 前面的文章中看到一个简单的适配器意图。 Eclipse中适配器的使用有略微不同和更多重复,在下面的例子,为了简单起见类与接口都放在一个文件中。 下面展现了类的继承关系
当我们想把橘子变成苹果,适配器就来了,下面我们看看他怎么做,在Eclipse中没有重复工作。
interface IAdaptable{
public Object getAdapter(Class adapter);
}
interface IApple extends IAdaptable{ }
interface IOrange{ }
class Orange implements IOrange{ }
interface IPear{ }
class Pear implements IPear{ }
public class Apple implements IApple{
@Override
public Object getAdapter(Class adapter) {
//the real story should be forwarding the request to the platform to get adapter
return PlatformAdapterManager.getAdapter(this, adapter);
}
}
class PlatformAdapterManager{
public static Object getAdapter(Object o, Class adapter){
if(adapter == IOrange.class){
if(o instanceof Apple){
return new Orange(); //Read code use an adapter to wrap the apple object and return an adapter object which implements IApple interface
}
}else if(adapter == IPear.class){
if(o instanceof Apple){
return new Pear();
}
}
return null; //return null when the class does not implement the interface.
}
}
PlatformAdapterManager 类是完全编造的,Eclipse中事实是platfrom得到一个适配器管理器然后返回一个正确的适配器。
public class Main {
public static void main(String args[]){
IApple apple = new Apple();
IOrange orange = (IOrange)apple.getAdapter(IOrange.class);
if(orange == null){
System.out.println("null");
}else{
System.out.println(orange);
}
IPear pear = (IPear)apple.getAdapter(IPear.class);
if(pear == null){
System.out.println("null");
}else{
System.out.println(pear);
}
}
}
输出
Output:
Orange@4fe5e2c3
Pear@23fc4bec
在类自己内部,这是一个途径实现getAdapter()方法,这个途径不需要注册在类中,因为他已经继承了getAdapter()方法。 以上文章翻译自: http://www.programcreek.com/2011/09/adapters-in-eclipse/