Factory design pattern

  • Factory
  • Factory Method
  • Static Factory
  • Abstract Factory

Factory

The best way to show the practical use case and benefits of using the Factory design pattern is by showing it in the example. The system you maintain includes a sales system and needs to generate invoices for customers. As your customers are from various countries, the invoices have to be suited for their needs. The examples of adjustments are:

  • the date format e.g. dd/mm/yyyy, mm/dd/yyyy;
  • the text direction — left-to-right or right-to-left;
  • the currency.

Factory Method

The solution proposed in the previous section has one significant issue. Excluding parts of the code that are specific to a particular country, there’s a part of the code that is common for each invoice such as file format or font settings (size, color, family, etc.).

source: pixabay.com

Static Factory

When the factory is ready another issue appeared. In the system, there were a few instances of the InvoiceFactory created. A few customers received an invoice with the same id. To eliminate this issue we could introduce a Static Factory. In this case, we can implement a simple in-memory solution that will store the ids of already generated invoices to prevent the described situation. In the case of duplication, an error will be thrown. The example implementation of the Static Factory may look as follows:

Abstract Factory

The described sales system has been successfully shipped into production. After some time a new set of requirements have been delivered to your team. Now, not only invoices but also internal sales reports have to be generated by the system. All types of documents have to be able to generate via a single interface. Moreover, the system must be ready to be extended by new document types in the future. The solution to this issue is to create an Abstract Factory. In short, the Abstract Factory uses other factories in its implementation and is a Factory at the same time. The example of the Abstract Factory is shown by the code below:

Summary

I hope, after reading the article the idea of the Factory design pattern is clear to you. I encourage you to try the described factories out in your projects. I also will be grateful if you give a clap and leave a comment! Below you’ll find some extra materials and sources.

Sources and extra materials

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store