The factory method pattern

The factory method pattern concerns defining an interface (or abstract class) method for creating dependency objects. This method is called a factory method. The class (or interface) that holds the factory method will be considered an abstract creator. The actual object creation process does not happen in the factory method directly. 

The concrete creators (which implement the factory method) will decide which dependent class to instantiate. In short, the dependent object is decided at runtime. This process has been described in the following diagram:

The factory pattern's implementation is a four-step process:

  1. Declaring the product (the abstract product type).
  2. Creating the concrete product.
  3. Defining the factory method – a creator.
  4. Creating concrete creators (concrete subclasses).

Let's understand these steps by using an example. Suppose you are developing an application for a message service provider. Initially, the company provides an SMS service for cellular devices. So, the first version of your application code is handling message distribution with SMS only, assuming that the bulk of code is written in the SMS class.

Gradually, the service becomes popular and you want to add other bulk message services, such as email, WhatsApp, and other social media message services. This requires code changes because you have added all the code to the SMS class. This change in code is required for every new messaging service that is introduced into the system in future.

The factory method pattern suggests that the solution to this problem will be inverting the object creation process from the client code (with a new operator) to a specific method: the factory method. The factory method defines a common interface that returns an abstract product type. A concrete product's creation is done in the child classes, which implement the factory method. The objects returned from the factory method are referred to as Product in the preceding diagram. First, let's define an abstract product type and its concrete implementation for the preceding example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.18.198