1. 单例模式(Singleton)

问题:全局只需要一个实例(如配置、缓存、数据库连接)。

核心:用一个变量标记是否已创建过实例,如果有就直接返回。

class Singleton {
  static #instance = null;

  constructor() {
    if (Singleton.#instance) {
      return Singleton.#instance;
    }
    Singleton.#instance = this;
  }
}

const a = new Singleton();
const b = new Singleton();
console.log(a === b); // true
package singleton

import "sync"

type singleton struct{}

var (
  instance *singleton
  once     sync.Once
)

func GetInstance() *singleton {
  once.Do(func() {
    instance = &singleton{}
  })
  return instance
}

在 JS 中,模块本身天然就是单例——import 同一个模块,拿到的始终是同一个对象。