Yeap. This is pretty easy (if I do not understand)
You should use the Prototype template template (or its variant, which I will show here)
This is useful if you do not know what the factory class may be prior to execution. Unlike AbstractFactory, where you can have different subclasses creating new types, but you can choose one based on certain conditions.
With a prototype, you can simply get the βoriginalβ object (prototype) entered into your application (due to the full Injection Dependency futures structure or a simple class name), and then create new instances.
Here is a code example showing how to do this with a change (not using the clone method, but newInstance )
public abstract class Application { public Application newInstance() { try { return this.getClass().newInstance();
And the rest of your code can be programmed into the Application interface:
public void doSomethingWith( Application application ) { System.out.println( application.toString() ); } public void startApplication( Application app ) {
Whenever you need a new instance, you simply call:
Application newApp = original.newInstance();
And that will create the correct type.
As you can see, the subclasses do not indicate how to create new subclasses, all in the base class.
Calling the newInstance method will always create a new instance of the same type.
source share