我想了很久,最后想出了一个不同的方法:
首先,我为您的RemoteVariable
课程添加了一个吸气剂:
protected RemoteDeviceProxy getWrappedProxy() {
return wrappedProxy;
}
其次,我创建了一个稍后将由工厂使用的构建器接口:
public interface RemoteVariableBuilder {
public <T> RemoteVariable<T> buildNewVariable(RemoteDeviceProxy wrappedProxy);
}
Boolean
然后我为...创建了非通用子类
public class RemoteBooleanVariable extends RemoteVariable<Boolean> implements RemoteVariableBuilder {
public RemoteBooleanVariable(RemoteDeviceProxy wrappedProxy) {
super(wrappedProxy);
}
@SuppressWarnings("unchecked")
@Override
public <T> RemoteVariable<T> buildNewVariable(RemoteDeviceProxy wrappedProxy) {
return (RemoteVariable<T>) new RemoteBooleanVariable(wrappedProxy);
}
@Override
public Boolean get() {
return getWrappedProxy().getBoolean();
}
@Override
public void set(Boolean value) {
getWrappedProxy().setBoolean(value);
}
}
...和整数...
public class RemoteIntegerBuilder extends RemoteVariable<Integer> implements RemoteVariableBuilder {
public RemoteIntegerBuilder(RemoteDeviceProxy wrappedProxy) {
super(wrappedProxy);
}
@SuppressWarnings("unchecked")
@Override
public <T> RemoteVariable<T> buildNewVariable(RemoteDeviceProxy wrappedProxy) {
return (RemoteVariable<T>) new RemoteIntegerBuilder(wrappedProxy);
}
@Override
public Integer get() {
return getWrappedProxy().getInteger();
}
@Override
public void set(Integer value) {
getWrappedProxy().setInteger(value);
}
}
实际上,一旦知道基类和接口,eclipse就创建了大部分代码。
最后一步是创建工厂
public class RemoteVariableFactory {
private static final Map<String, RemoteVariableBuilder> BUILDERS = new HashMap<>();
static {
BUILDERS.put(Boolean.class.getName(), new RemoteBooleanVariable(null));
BUILDERS.put(Integer.class.getName(), new RemoteIntegerBuilder(null));
// add more builders here
}
public static <T> RemoteVariable<T> getRemoteVariable(RemoteDeviceProxy wrappedProxy, Class<T> typeClass) {
RemoteVariableBuilder remoteVariableBuilder = BUILDERS.get(typeClass.getName());
if (remoteVariableBuilder == null) {
return null; // or throw an exception whichever is better in your case
}
return remoteVariableBuilder.buildNewVariable(wrappedProxy);
}
}
现在我们准备好创建新的 RemoteVariables...
RemoteVariable<Boolean> var1 = RemoteVariableFactory.getRemoteVariable(new RemoteDevice(), Boolean.class);
RemoteVariable<Integer> var2 = RemoteVariableFactory.getRemoteVariable(new RemoteDevice(), Integer.class);
总结一下,让我们快速比较一下 Eng.Fouad 的答案:
坏处:
优势:
- 您只需在工厂的静态块中添加一行,而不是在 RemoteVariable 中的 getter 和 setter 中添加两个新 if 块
- get 和 set 不必每次都通过 if-else-blocks