Zachary W. Huang

Home Projects Blog Guides Resume

Singleton

Idea: Manage (or ensure) a single instance of a class and provide global access to it.

class DatabaseSingleton {
  static _instance?: DatabaseSingleton = undefined;
  data: any = {};

  // prevents class from being directly instantiated
  protected constructor() {}

  static instance(): DatabaseSingleton {
    if (DatabaseSingleton._instance === undefined) {
      DatabaseSingleton._instance = new DatabaseSingleton();
    }
    return DatabaseSingleton._instance;
  }

  connect() {
    this.data = {"a": 1, "b": 2, "c": 3};
  }

  getData(key: string) {
    return this.data[key];
  }
}

function main() {
  const db = DatabaseSingleton.instance();
  db.connect();
  console.log(db.getData("a")) // "1"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024