我想为我的泛型类创建一个工厂。我有Device基类:
public abstract class Device<T> {
T stateVariable;
private String name;
public Device(T stateVariable, String name) {
super();
this.name = name;
this.stateVariable = stateVariable;
}
// getters & setters
abstract void changeActualState(T changeVariable);
}
TV类扩展了设备:
public class TV<T> extends Device<T>{
public TV(T stateVariable, String name) {
super(stateVariable, name);
}
@Override
void changeActualState(T changeVariable) {
if(!changeVariable.equals(stateVariable)){
System.out.println("The TV now is " + changeVariable);
setStateVariable(changeVariable);
}
}
}
还有Therme类,它也扩展了Device类:
public class Therme<T> extends Device<T> {
public Therme(T stateVariable, String name) {
super(stateVariable, name);
}
@Override
void changeActualState(T changeVariable) {
if(!changeVariable.equals(stateVariable)){
System.out.println("The temperature changed to " + changeVariable);
setStateVariable(changeVariable);
}
}
}
我也有一个枚举:
enum Type{
TV, Therme
}
我想创建一个工厂,取决于enum的类型来制作特定的类。
答案 0 :(得分:0)
实现这一目标有很多选择。这是将设备直接嵌入枚举中的一个:
enum Type {
TV {
@Override
protected <T> BiFunction<T, String, Device<T>> deviceCreator() {
return device.TV::new;
}
},
Therme {
@Override
protected <T> BiFunction<T, String, Device<T>> deviceCreator() {
return device.Therme::new;
}
};
protected abstract <T> BiFunction<T, String, Device<T>> deviceCreator();
public <T> Device<T> createDevice(T stateVariable, String name) {
return this.<T>deviceCreator().apply(stateVariable, name);
}
}