- Refers to the newly created object through a common interface
- Client asks Factory class to create object by passing the information it needs
- Creates objects without exposing the instantiation logic to the client
Where to use & benefits
- A class wants its subclasses to specify the object.
- need flexibility in adding new types of objects that must be created by the class
- Hide concrete classes from the client.
- provides hooks for subclasses is more flexible than creating objects directly
Implementation
- Interface Color implemented by 3 concrete classes Red, Green & Blue
- Class ColorFactory having method to create object of Red, Green or Blue based on parameter passed and return into Color type reference variable
- Client will create a ColorFactory object and call its method by passing parameter
Examples of Factories
- Provide an XML parser :
- javax.xml.parsers.DocumentBuilderFactory or SAXParserFactory
- Allows users to decide which protocol to use
- java.net.URLConnection
No comments:
Post a Comment
Note: only a member of this blog may post a comment.