需要知道此代码是否有问题。使用Class作为ComputerFactory的键。好处是,添加新的计算机子类时,无需在工厂类中进行任何更改。此外,借助泛型,我只能对Computer factory强制使用有效密钥。
public abstract class Computer {
protected String name;
@Override
public String toString(){
return "Computer type: "+name;
}
}
public class Pc extends Computer {
public Pc() {
this.name = "PC";
}
}
public class Server extends Computer {
public Server() {
this.name = "Server";
}
}
public class ComputerFactory {
public static Computer getComputer(Class<? extends Computer> type) {
Computer computer = null;
if (!Computer.class.equals(type) && Computer.class.equals(type.getSuperclass())) {
try {
computer = type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
return computer;
}
}
public class Test {
public static void main(String args[]) {
Computer c = ComputerFactory.getComputer(Server.class);
if (c != null)
System.out.println(c.toString());
}
}