Contents

About design pattern creational(2)

   Jul 9, 2023     2 min read

This is an article about the generation pattern among design patterns.

In the last post, we looked at the Singleton pattern. In a nutshell, the Singleton pattern is a technique for creating only one instance and making it globally accessible.

In this article, we’ll learn about the Factory pattern, which is one of the creation patterns.

What is the Factory pattern?

It is a technique that encapsulates the object creation process and provides flexibility by introducing a separate factory class that is responsible for creating objects.

What is encapsulation?

Hiding an object’s internal implementation from the outside world, allowing you to interact with the object solely through externally provided interfaces. This protects the object’s state and behavior, and protects the object against improper access from the outside world. An object can only manipulate data and change its state through methods.

I’d like to show you an example of applying the factory pattern with Type Script (TS).

Example

// Interface: defines the methods that the objects to be created must implement.
interface Product {
  operation(): void;
}

// Concrete object classes: these are the concrete objects that implement the interface.
class ConcreteProductA implements Product {
  operation(): void {
    console.log("ConcreteProductA operation");
  }
}

class ConcreteProductB implements Product {
  operation(): void {
    console.log("ConcreteProductB operation");
  }
}

// Factory class: responsible for creating and returning objects.
class Factory {
  createProduct(type: string): Product {
    if (type === "A") {
      return new ConcreteProductA();
    } else if (type === "B") {
      return new ConcreteProductB();
    } else {
      throw new Error("Invalid product type");
    }
  }
}

// Client code
const factory = new Factory();

const productA = factory.createProduct("A");
productA.operation(); // Output: ConcreteProductA operation

const productB = factory.createProduct("B");
productB.operation(); // Output: ConcreteProductB operation