Factory design pattern

Design patterns

Factory is a design pattern, from the creational patterns category used in OOP to create objects without need to specify class full name. In other words without using new function.

The essence of the Factory method Pattern is to define an interface for creating an object and let the classes that implement the interface decide which class to instantiate.

 

The main reason for use factory patterns is to create objects that are complex to create. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction. and others. Factory pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

 

Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized set-up and tear-down concerns.

 

The pattern is also used often, in frameworks, and libraries, when is need to create documents of various types (pdf, doc) or parsers (xml, json, custom format).

 

Factory design pattern encapsulate the creation of objects. This can be useful, if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.

 

Let take couple example (that are somehow same example from various perspective):

1. In complex systems, lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a xml file. You want to change it to a different class that reads from the database and all the code references are to original class that reads from a xml file. This is where the factory pattern comes in handy.

 

2. Other scenario is: you want to create an application that read different text formats like txt, xml, pdf, doc and others. Factory pattern is very useful because if the pattern is applied you will have a separate class for each file type and application can swich from one file type to other and read documents without making difference between files types. This approach is very useful if you want to add a new file type that application supports or if you want to remove one also.If the reading logic of all file types it will be in a one class it would be very difficult to modify and maintain code.


Add comment
 
 
 

Comments