vendredi 6 novembre 2015

Is there a better way to implement a simple Factory with two conditions?

I have the following class structure:

MyClass
  FirstClass
    FirstClassVersion1
    FirstClassVersion2
  SecondClass
    SecondClassVersion1
    SecondClassVersion2

At a certain point i need a reference of MyClass according with class number and class version, so i created a simple factory. But my factory is a little complex as follow:

public class MyClassFactory {

    public static MyClass createMyClass(int classNumber, int classVersion) throws Exception {
        if (classNumber == 1) {
            if (classVersion == 1) {
                return new FirstClassVersion1();
            } else if (classVersion == 2) {
                return new FirstClassVersion2();
            }
        } else if (classNumber == 2) {
            if (classVersion == 1) {
                return new SecondClassVersion1();
            } else if (classVersion == 2) {
                return new SecondClassVersion2();
            }
        }

        throw new Exception("...");
    }
}

Is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire