70 likes | 473 Views
What is Factory. Category: Creational Also known as Abstract Factory+Factory Method Hides the details of object creation from the client. Hides the type of object being created from the client. How to Use Factory. Implementation Details
E N D
What is Factory • Category: Creational • Also known as Abstract Factory+Factory Method • Hides the details of object creation from the client. • Hides the type of object being created from the client.
How to Use Factory • Implementation Details • Create a Factory/Creator interface that defines the factory methods. • Create concrete implementations of the Factory interface, with specific implementations of the factory methods. • Usage Details • Instantiate a concrete instance of the Factory interface, and refer to it as the interface in your code
Class Diagram From (Stephen Stelting, Olav Maassen, Applied Java™ Patterns)
Why Factory • The factory pattern groups a ‘theme’ of objects together in one creator object. • The theme of objects for the application can be changed by simply plugging a different factory implementation in. • The application is written specifically to interface-level APIs, inherently making it more flexible.
When to Use Factory • Anytime there are: • Many objects involved in a single feature • Many forms of a single feature • Factory is generally useful anytime the application uses Interfaces. By using the factory class, changing the underlying implementation of the interfaces is a one-line change.
In the Real World • Factory is often used to swap out features of the application for different needs, such as the type of editor to show in a text editor. • The first step would be to introduce an interface called EditorFactory. This method may have methods to get toolbars, rendering objects, and a multitude of other useful features. • If the file ends in ‘.doc’, the objects involved in the editor should work with Word documents, so we should use a WordEditorFactory.