Factory
Probably one of the most frequently used creational patterns, a Factory is a class which produces objects for clients usage.
Intent
- Creates an object with certain rules, without exposing the instantiation logic
- Refers to the newly created object through a common interface
Here is a sample factory:
Then you can create a wasp by simply calling WaspFactory.createWasp(); from the client. The good thing about this pattern is that with a little bit of imagination, you can create various factories abstract factories which may serve you well in terms of maintenance.
Here is an example of how. Say we have a WaspFactory interface.
Above you may see the implementations of Wasp interface. Pay attention to keyword protected at definition of constructors. This behaviour enforces that only a class in the exact same package can create a Hornet or a PollenWasp. Now lets create the factory that will create these wasps.
Above you can see the WaspFactory as a Singleton with an enumeration of wasp types to pick. Creating this class in same package will let the factory to create these wasps while encapsulating them from rest. Now lets see the usage of this code.
WaspFactory wf = WaspFactory.getInstance();
wf.createWasp(WaspFactory.WaspType.HORNET); // Hornet created.
wf.createWasp(WaspFactory.WaspType.POLLEN_WASP); //Pollen Wasp created.