jeudi 28 juin 2018

Factory pattern with class as key

Need to know if there is any problem with this code. Have used Class as key for ComputerFactory. The advantage is that you don't need to make any changes in factory class when you add a new computer subclass. Further, with the help of generics, I am able to enforce only the valid keys for 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());
}

}

Aucun commentaire:

Enregistrer un commentaire