YouTip LogoYouTip

Design Patterns - Singleton and Factory

Singleton Pattern

class Singleton {
    static instance;
    static getInstance() {
        if (!this.instance) this.instance = new Singleton();
        return this.instance;
    }
}

Factory Pattern

class Factory {
    static create(type) {
        if (type === "car") return new Car();
        if (type === "bike") return new Bike();
    }
}

Summary

  • Singleton ensures one instance
  • Factory creates objects without specifying exact class
← Data Structures - Arrays and LHTML DOM Tutorial - Selection β†’