In this blog post, Justin Albano talks about the Factory Method Pattern and gives us an example.
The Textbook Definition
According to the Gang of Four book that defined the technique, the intent of the Factory Method pattern is as follows:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Using the Factory Method involves creating two sets of interfaces: “(1) the product interface that constitutes the object to be created and (2) the creator interface that constitutes the object that will instantiate the product.” The UML diagram for the Factory Methods is below:
The author explains the UML diagram as the following:
Using the general pattern, we build a Creator interface, which includes one or more Factory Methods, as well as any number of other methods. This interface may also be an abstract class with defined methods or even a default implementation of the Factory Method that returns a default instance of Product. From this interface, a set of ConcreteCreator classes are created that return desired ConcreteProduct instances that implement the Product interface.
An Example in Java
In the end you should be able to do something like this:
PersistedFile file =
new PersistedFile("/foo/bar/text.txt", "Hello, world!", new Sha256Encryptor());
View complete example here
Colloquial Definition
A method whose sole responsibility is to abstract the creation process of an object and return that object.
I chose this resource because I am interested to learn new implementations of popular design patterns such as the Factory Method. This resource gave a detailed explanation along with other patterns that can be good alternatives to the Factory Method pattern like the Template Method pattern and Strategy Pattern. I believe the content of the article is very detailed and informative. The example they used is very interesting and I’m going to implement the code myself to test it out. I plan to use this and many other design patterns in the future. I learned more about the Factory Pattern method and when it is appropriate to use it.
The post Java: The Factory Method Pattern appeared first on code friendly.
From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.