Factory Method

Factory method is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.

A simple problem

Imagine that you are creating a logistics management application. The first version of your app can only handle transportation by trucks, so the bulk of your code inside the Truck class.

After a while, your app becomes popular, and you receive many requests from other transportation companies of different communications ways to incorporate into the app.

you are very happy to know it but know you have a big problem, most of your code is coupled to the Truck class. Add another functionality like Ships or aeroplane would require making changes to the entire codebase. Moreover, if later you decide to add another type of transportation to the app, you will probably need to make all of the changes again.

As a result, you will end up with smelly code.

Solution

The factory method pattern suggests that you replace direct object construction calls with calls to a special factory method.

Structure

  1. The product declares the interface, which is common to all objects that can be produced by the creator and its subclasses.
  2. Concrete Products are different implementations of the product interface.
  3. The creator class declares the factory method that returns new product objects. It’s important that the return type of this method matches the product interface.
  4. Concrete creators override the base factory method so it returns a different type of product.

Code

You can to see the code in the next GITHUB repository here.

Applicability

use the Factory Method when you don’t know beforehand the exact type and dependencies of the objects your code should work with.

The Factory Method separates product construction code from the code that actually uses the product. Therefore it’s easier to extend the product construction code independently for the rest of the code.

For example, to add a new product type to the app, you’ll only to create a new creator subcalass and override the factory method in it.

Avatar de Rolando Castillo

Escrito por:

Deja un comentario