Easy patterns: Factory method

Ruslan Malogulko
ITNEXT
Published in
2 min readJun 25, 2018

--

This article is created in continuation to series of easy patterns description and describes Factory method pattern which is needed to delegate instantiation logic to nesting classes at runtime.

Currently you can find articles for such patterns:

Creational patterns:

Simple Factory

Factory method (this article)

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

In object oriented languages this pattern helps to instantiate new items with the help of generation methods in the nested classes. This helps to avoid mentioning specific classes in parent class and completely delegate type definition to the nested ones. Even more, class type can be defined at runtime.

Example of use

In example we’ve created an parent vehicle class Vehicle and two nesting classes: Car and Bicycle. Also were created base SpecializedRentalAgency with abstract factory method addVehicle, which implemented in nested classes CarRentalAgency and BicycleRentalAgency to return needed class type instances. But overall rental process described in method lendVehicle the same for them so implemented in base SpecializedRentalAgency class.

Pros

Factory method helps to solve instantiation problem when it’s not defined, which class instances are needed. It can be defined at execution period.

The system keeps independent from class instantiation process and separated from this concern totally. Also this pattern keeps system extendable and flexible in adding new class types to be instantiated.

Cons

Instantiation process should be under control because of its dynamic nature. Additional checkers for class type existence should be added to avoid getting errors on class type existence, its type compatibility and so on.

Conclusion

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

--

--