Design Patterns In TypeScript — Factory
How to create an object without exposing the creation logic
The Factory Pattern is one of the core design pattern principles for creating an object. It allows clients to create objects using a common interface. In TypeScript, there are many different ways in which you can use the factory pattern to make your code cleaner and more concise. In this article, we’ll demonstrate how to create a factory pattern using TypeScript Generics.
What is Factory?
The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software define the Factory Pattern as:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
In other words, the factory design pattern defines an interface or an abstract class and allows subclasses to decide which object to instantiate. In that way, we are adding polymorphic behavior to the instantiation.
How Does It Work?
The client calls the create function with a subclass from a factory instead of creating objects directly with a concrete class. As a factory corresponds to a single interface variant, all its objects will be compatible.
Each client calls create with a subclass of a factory interface and receives a class to be instantiated. This class is related in some way to the subclass, and each client can behave differently based on that subclass.
The purpose of this example is to create a user authentication factory for any type of user (ordinary, administrator, moderator, etc) in an application.
First, let’s define the
BaseUser interface which is the main interface in our factory, and its subclasses that will be used in
Authentication to define the
signOut methods. In the following code snippet, we’ll illustrate two implementations of the