以类别为键的工厂模式

时间:2018-06-29 05:59:31

标签: java design-patterns factory-pattern

需要知道此代码是否有问题。使用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());
    }
}

0 个答案:

没有答案