简体   繁体   中英

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?

Here's another idea:

public class MyClassFactory {

    private MyClassFactory instance = new MyClassFactory();

    private MyClassFactory() {}

    public MyClassFactory getInstance() { return instance; }

    public MyClass create(Class clazz) throws Exception {
       return clazz.newInstance();
    }
}

Embellish this as needed (eg stronger type checks using generics).

Your way requires that you modify the factory every time you extend the class. That can't scale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM