Summary on basis of the book ,,Design Patterns: Elements of Reusable Object-Oriented Software'', by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley, 1995.
abstract class Creator{
abstract class Creator{
abstract createProduct();We use it when a class (Creator) needs to create and use an object (Product), but it does not need to know the type of the object.
doSomething() {
...
Product p = createProduct();
p.blaBlaBla();
...
}
}
We make this class abstract, and let its subclasses implement the method factoryMethod(), which will create and return the concrete object. The factoryMethod() method is then for example used in the abstract Creator whenever the Product of unknown type was needed.
We can also use this methd when we want to specify the object type to create in Creator subclasses.
Consequences:
- (+) the code in abstract Creator is not application-specific, not bound to any specific product implementation
- (-) each time we want to create specific Product, we have to subclass Creator class - so this method is good if we would do it anyway, otherwise it is just making the application more complicated
- we can also use it pattern when Creator has delegated part of its responsibilities to another class (Manipulator); then in Manipulator we can also use the factoryMethod() methods (in the book the Manipulator class was abstract, and its various subclasses were using factoryMethod() methods of corresponding subclasses of Creator class; that is why this case was called the case of parralel class hierarchy
- Creator does not have to be abstract; it can be concrete and provide default Product implementation
- factoryMethod() can take a parameter telling which object to instantiate; in such case the Creator would create some objects, the rest can be created by Creator's subclasses (but in such case these subclasses must call the Creator's factoryMethod() method at the end)
- and many other variations..
Comments
Want to leave a comment? Visit this post's issue page
on GitHub and just post your comment as the issue's comment (you'll need a GitHub account. What? Like you don't have one yet?!).
Comments: