4

I have an interface:

public interface MyInterface{}

And two implementations:

public class Imp1 implements MyInterface {}
public class Imp2 implements MyInterface {}

My program is a CLI. I want to have some class, which would take command-line args, parse it and create new instance of correct implementation:

public class MyFactory {
    public MyInterface getMyInterface(CommandLineArgs args) {
       ....
    }
}

Is there a pattern to use here? I am not sure that abstract factory pattern suits it, as I have only one implementation of the factory.

If it is not the correct way to do it (why?), then how it is more acceptable to do it?

Thanks in advance

6

This is a usecase for the factory pattern or a mixture of factory and builder pattern. You would pass the factory the parameter for the requested variant and get an instantiated object back. If there is some further configuration necessary, you could abstract this with the builder pattern.

I am not sure that abstract factory pattern suits it, as I have only one implementation of the factory.

Depending on your actual requirements, a simple factory would do.

  • 2
    MyInterface instance = MyInterfaceFactory.createInstanceFromArgs(args); // Ta-da! – Neil Apr 9 '18 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.