Factory Method Pattern
Factory method pattern is a very light weight pattern. It is used in the scenarios where we do not want the client directly refer to the concrete classes for object instantiation, rather we handover the responsibility to a "Creator" class which will be instantiating the appropriate object based on the client requirement and thus centralizing the code of object creation. And client deals with interface instead of concrete classes. Factory method is also termed as "Virtual Constructor" in C++.
Intent & Motivation of Factory Pattern: "Define an interface for creating an object, but let subclasses decide which class to instantiate." Since library knows when an object needs to be created, but not what kind of object is going to be created. As this is specific to the application it can use the Factory Method.
Factory pattern is used when:
- Flexibility is important.
- Objects can be extended in subclasses
- There is a specific reason why one subclass would be chosen over another. This logic forms part of the Factory Method.
We can think of below scenarios where Factory method pattern can be implemented:
- Set upa system to draw circles, squares, and lines. Create a Factory Method that instantiates one of these classes at random and uses it to draw a shape of random size on the screen. Run the program to see what interesting shapes you get.
A company has a web site to display test results from a plain text file. The company recently purchased a new computer that produces a binary data file, and it has another new machine on the way that will possibly produce a different data file. The company is also considering switching to an XML format. Write a system to deal with such changes. The web site just needs data to display; your job is to provide the specified data format for the web site.
We have list of movies categorized into genre. Client wants to get the specific genre movies. Here client can deal with movie interface and based on his parameter passed to FactoryMethod he will get the list of movies.
So let us work on the 3rd movie list example. More...