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
1 Answer 1
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.
-
2MyInterface instance = MyInterfaceFactory.createInstanceFromArgs(args); // Ta-da!Neil– Neil2018年04月09日 10:40:48 +00:00Commented Apr 9, 2018 at 10:40
Explore related questions
See similar questions with these tags.