02 Mar 2023

Creational Design Patterns

  • Singleton:
    • a type of object that can only be instantiated once
    • often used in C++
class Settings {
    static instance: Settings;
    public readonly mode = "dark";

    private constructor() { // a private constructor ensures no one else can create it
        ...
    };
  • Prototype:

    • a clone
    • alternative to inheritance, which can create complex tree patterns
    • instead of inheriting from a class it inherits form an object that’s already been created
    • creates a flat prototype chain
  • Builder:

    • building object step by step using methods instead of all at once

Do:

addKetchup() {
 this.ketchup = true;
}

Don’t:

constructor(
    public ketchup: boolean;
) {};
  • Factory:

    • e.g. We have 2 similar classes (eg. one for iOS one for Android) we could do this:

Do:

class ButtonFactory {
    createButton(os: string) : IOSButton | AndroidButton {
        if (os === 'ios') {
                return new IOSButton();
        else {
                return new AndroidButton();
        }

const button = ButtonFactory('ios');

Don’t:

const button = os === 'ios' ? 
                             new IOSButton :
                             new AndroidButton;