Properties:
- Hides details of class instance creation and actual class implementation. This allows easy replacement of class implementation and gives flexibility to change the way new instance construction is done.
- Creates and abstraction layer between client code and object needs to be created, thus facilitates loose coupling.
- Client provides attributes of the object it needs to create and defers instantion to factory. It is not obligatory to supply any attributes though.
- Factory creates a suitable class instance according to attributes supplied.
- The problem with Factory pattern is when a new implementation is added Factory class needs to be modified which vilotaes the open-closed* principle.
Implementation:
- Factory class has method named createXYZ which takes necessary arguments.
- createXYZ method creates an concrete XYZ instance and retuns to client.
- Client uses returned XYZ instance without ever knowing actual concrete class used.
Java Standard Library Implementations:
- Javax.swing.PopupFactory
Example Usage:
PopupFactory factory = PopupFactory.getSharedInstance();
// createXYZ method
// Popup implementation may be one of LightWeightPopup,
// MediumLightWeightPopup, HeawyLightWeightPopup implementations.
Popup popup = factory.getPopup(owner, contents, x, y);
popup.show();
// Some logic.
...
popup.hide();
Comments
Post a Comment