Properties:
- The same with factory pattern except that Factory class is abstract class and createXYZ method is made abstract.
- Subclasses of the factory class implements createXYZ method thus subclass determines how instance is created.
- Identified by abstract Factory class and abstract creation method.
Implementation:
- Factory class has an abstract method named createXYZ which takes necessary arguments.
- Abstract createXYZ method is implemented by subclasses of Factory class. A Subclass creates an appropriate concrete XYZ instance and retuns.
- Client uses returned XYZ instance without ever knowing actual implementation.
Java Standard Library Implementations:
- javax.xml.parsers.DocumentBuilderFactory
- javax.xml.parsers.SAXParserFactory
Example Usage:
try {
// returns com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl instance.
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// Focus this part:Factory Method pattern is in use.
// Note That: newDocumentBuilder() is an abstrack method in DocumentBuilderFactory class.
// Thus newDocumentBuilder() method defined in
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl is used.
DocumentBuilder builder = factory.newDocumentBuilder();
// builder instance is used.
Document doc = builder.parse(new File(args[0]));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Comments
Post a Comment