学习了What is IAdaptable?这篇文章,有点困惑,干脆做个demo巩固下,包括三个部分:OldObject 、NewObject和工厂类YearFactory
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
// 实现了IAdaptable 接口
public class OldObject implements IAdaptable {
private String yearmonthday;
public String getYearmonthday() {
return yearmonthday;
}
public void setYearmonthday(String yearmonthday) {
this.yearmonthday = yearmonthday;
}
public Object getAdapter(Class adapter) {
return Platform.getAdapterManager().getAdapter(this, adapter);
}
}
public class NewObject {
private String year;
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
完成具体的转换
import org.eclipse.core.runtime.IAdapterFactory;
public class YearFactory implements IAdapterFactory {
private static final Class[] types = { NewObject.class };
public Object getAdapter(Object old, Class clazz) {
if (clazz == NewObject.class && old instanceof OldObject) {
NewObject objectNew= new NewObject();
objectNew.setYear(((OldObject) old).getYearmonthday().substring(2)); //随意的规则
return objectNew;
} else {
return null;
}
}
public Class[] getAdapterList() {
return types;
}
}
调用转换的代码:
Platform.getAdapterManager().registerAdapters(new YearFactory(), OldObject.class);
OldObject old = new OldObject();
old.setYearmonthday("20070914");
Object adaptable = old.getAdapter(NewObject.class);
if (adaptable != null) {
NewObject node = (NewObject) adaptable;
System.out.println(node.getYear());
}
总结:
术语:源对象、转换类型、工厂
目的:实现两个不相关对象的转换
(1)源对象需要实现IAdaptable接口,或者继承PlatformObject抽象类
(2)在源对象IAdaptable接口方法getAdapter的实现可以如下,即直接转发给AdapterManager的getAdapter()方法
public Object getAdapter(Class adapter) {
return Platform.getAdapterManager().getAdapter(this, adapter);
}
(3)实现转换工厂类,具体负责转换,需要实现IAdapterFactory接口,其接口方法getAdapterList()负责通知AdapterManager转换类型,
而getAdapter方法具体完成转换
(4)将转换工厂类注册到AdapterManager:
Platform.getAdapterManager().registerAdapters(new YearFactory(), OldObject.class);
这样的好处在于,如果源对象需要转换到多个不相关的对象的时候,不需要修改源对象,而直接转发给相应的工厂类,这样在一定程度上保护了源对象免于修改,
而是修改或者增加新的工厂类。