Easy patterns: Simple Factory

Ruslan Malogulko
ITNEXT
Published in
2 min readJun 23, 2018

--

This article is created in continuation to series of easy patterns description and describes creational pattern Simple Factory for continuous instance creation in the simple and quick manner.

Currently you can find articles for such patterns:

Creational patterns:

Simple Factory (this article)

Factory method

Builder

Singleton

Abstract factory

Prototype

Structural patterns:

Adapter

Decorator

Bridge

Composite

Facade

Flyweight

Proxy

Behavioral patterns:

Visitor

Mediator

Observer

Memento

Iterator

Chain Of Responsibility

Strategy

State

The main essence

The Simple Factory pattern is the simplest class which has methods for creation other class instances. For example if you need to create a tons of instances for some specific class, it’s much easier to use method which returns instances for you. That’s the main idea. Factory helps us to keep all objects creation in one place and avoid of spreading new key value across codebase.

Example of use

In this example we create two classes: one for box and one for tape. We’re creating gift boxes pack. Once we need squared boxes (width === height), it’s easier to create a factory class with method which returns them for us in iteration by defining sizes in an array. The same we’re doing for tapes to glue boxes later. In the method which returns new object for box and tape we included additional business logic, that notifies us in a console which object is created at runtime (see the bottom of example code).

So, when you have a business logic which should be added to creation class instance, it’s easier to use Simple Factory and not spreading this logic over the code.

Weak places

Unfortunately simplicity leads us to some limitations — no control of creation process. You are limited with params you can pass. If you need to do more than just simple creation, you would prefer more advanced patterns: Factory Method, Abstract Factory, Builder etc.

Conclusion

If you found this article helpful, please hit the 👏 button and feel free to comment below!

--

--