简体   繁体   中英

Java factory pattern with different initialisation object types

I'm using the factory pattern to create instances, and want to initialise these instances with different objects. At the moment I'm simply casting the object, but this doesn't feel right.

public interface IGenerator {
    public IGeneratedObject generate();
}

public class FirstGenerator implements IGenerator {

    private List<FirstObject> list;

    public FirstGenerator(List<FirstObject> list) {
        this.list = list;
    }

    public IGeneratedObject generate() {
        return doSomeStuff(list);
    }
}

public class SecondGenerator implements IGenerator {

    private UnrelatedObject obj;

    public SecondGenerator(UnrelatedObject obj) {
        this.obj = obj;
    }

    public IGeneratedObject generate() {
        return doOtherThingsStuff(obj);
    }
}

public class GeneratorFactory {

    public static IGenerator createGenerator(GeneratorType type, Object object) {

        switch (type) {

        case FIRST:
            return new FirstGenerator((List<FirstObject>) object);
        case SECOND:
            return new SecondGenerator((UnrelatedObject) object);
        }

        return null;
    }
}

Usage would then be as follows:

IGenerator gen1 = GeneratorFactory.createGenerator(GeneratorType.FIRST, listOfFirstObjects);

IGenerator gen2 = GeneratorFactory.createGenerator(GeneratorType.SECOND, unrelatedObj);

FirstObject and UnrelatedObject aren't related at the moment - no common base class or interfaces.

In the factory method, the compiler of course shows an 'Unchecked cast from...' warning.

Is there a better way? It seems like a situation where generics could be used, but is this unfeasible due to the objects not being related?

Could you create factory class so that the usage would be as below?

IGenerator gen1 = GeneratorFactory.createGeneratorFirst(listOfFirstObjects);

IGenerator gen2 = GeneratorFactory.createGeneratorSecond(unrelatedObj);

There is no reason to have method "create generator".

Creating generator is encapsulated by constructor and class type itself.

Using IGenerator gen1 = new FirstGenerator((List<FirstObject>) object); is completely fine.

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