Typescript Factory Pattern without Switch or If Else

Factory pattern is a well known creator pattern. Problem with factory pattern is whenever there is a new concrete class that will be instantiate by the creator class (that have factory method), you have to add new ‘case’ in a switch or if / else.

So this violate the Open Close Principle which states open for extensions but close for modifications.

Code below using typescript, but the concept is same for other programming language.

Factory Pattern with Switch or If Else

If you want to add Square shape, we need to add another case in the factory.

The concept is the same with If Else

So I need to open my factory class every time there is a new shape to be add in.

Factory Pattern without Switch & If / Else

There are 3 main classes

1) Factory class
– it will import the shape class files in the folder /shapes
– instantiate the object based on shape type

2) Shape abstract class
– abstract method of getType()

3) Shape concrete class
– implement the getType() to tell what type is the shape e.g round
– located in /shapes folder

The concrete class Shape will implement a function to tell it is what kind of Shape.

The factory class will import all the shape file path and instantiate the object when call by user class.

How To Use It?

Impact

It requires async / await because needs to load dynamically the shape class.

This factory pattern can’t be used in a constructor.