Contents

About design pattern creational(3)

   Jul 10, 2023     2 min read

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

In the last post, we introduced the Factory pattern. In a nutshell, it’s a technique that encapsulates the object creation process and provides flexibility by introducing a separate factory class responsible for object creation.

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

What is the Abstract Factory pattern?

Before we get into this, it’s important to understand the concept of the factory pattern. In the factory pattern, a single factory class returns a variety of subclasses using conditional statements based on argument values.

The abstract factory pattern excludes conditional statements from generating subclasses from a factory class.

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

Example

// Abstract Factory interface
interface AbstractFactory {
  createProduct(): Product;
}

// WindowsFactory class
export class WindowsFactory implements AbstractFactory {
  createProduct(): Product {
    return new WindowsProduct();
  }
}

// MacFactory class
export class MacFactory implements AbstractFactory {
  createProduct(): Product {
    return new MacButton();
  }
}

// abstract product class
abstract class Product {
  abstract operation(): string;
}

// Product class in WindowsFactory
class WindowsProduct extends Product {
  operation(): string {
    return "Rendering a Windows Product";
  }
}

// Product class for MacFactory
class MacButton extends Product {
  operation(): string {
    return "Rendering a Mac Product ";
  }
}

// Client code
function createUI(factory: AbstractFactory) {
  const button = factory.createProduct();

  button.operation();
}

// Example usage
const windowsFactory = new WindowsFactory();
createUI(windowsFactory);

const macFactory = new MacFactory();
createUI(macFactory);