1
1

More than 1 year has passed since last update.

JavaScriptのSingleton パターン

Last updated at Posted at 2022-05-29

Classバージョン

export class Singleton {
  private static instance: Singleton | null

  public static getInstance(): Singleton {
    if (Singleton.instance)
      return Singleton.instance
    Singleton.instance = new Singleton()
    return Singleton.instance
  }

  private constructor() {
  }
}

Functionバージョン

function genGetInstanceMethod() {
  let instance;

  class Singleton {

  }
  
  // getInstanceをmethodとして返す
  return () => {
    // Closureを利用する
    if (instance == null) {
      instance = new Singleton()
    }
    return instance
  }
}

const getInstance = genGetInstanceMethod()
const i1 = getInstance()
const i2 = getInstance()

console.log(i1 === i2) // true
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1