Factory Method Key Features Ü Defines an interface for creating objects without needing to know each object’s type Ü Encapsulates the instantiation of concrete types Ü Leaves the details of instantiation to subclasses
Factory Method UML
Factory Method Document Example abstract class Document. Factory { abstract class Document { public abstract Document get. Document(); . . . } } class HTMLCreator extends Document. Factory { class HTMLDocument extends Document { public Document get. Document() { return new HTMLDocument(); . . . } } } class XMLCreator extends Document. Factory { class XMLDocument extends Document { public Document get. Document() { return new XMLDocument(); } } . . . }
Factory Method Encapsulation Example class Document. Factory { public static Document get. Document(String file) { int type = get. Type(file); switch(type) { case Document. Factory. HTML: return new HTMLDocument(file); case Document. Factory. XML: return new XMLDocument(file); . . . } }
Factory Method Benefits Ü Types of created objects can be determined at runtime Ü Common interface allows for easier use by client classes Ü Useful for toolkits and frameworks Limitations Ü Might need to subclass the factory to create concrete things (e. g. , need to create an HTMLCreator to create an HTMLDocument)