weikee94 / design-patterns

Design Patterns
0 stars 0 forks source link

Singleton Pattern #1

Open weikee94 opened 2 years ago

weikee94 commented 2 years ago
var Singleton = function (name) {
  this.name = name;
};

// 这个就是那个变量用来标示是否为某个类创建过对象
Singleton.instance = null;
Singleton.prototype.getName = function () {
  alert(this.name);
};
Singleton.getInstance = function (name) {
  // 每次在调用时先检查是否创建过
  if (!this.instance) {
    this.instance = new Singleton(name);
  }
  return this.instance;
};
var a = Singleton.getInstance("a");
var b = Singleton.getInstance("b");
alert(a === b);
weikee94 commented 11 months ago
class SingleObject {
  // 这里的login 不是静态的
  // 因为每次初始化,这个都会存在每个instance 里
  login() {
    console.log("login");
  }
}

// getInstance 这个就是静态,因为它被挂载到SingleObject 上
// 所以无论new 多少次,只会有一个
SingleObject.getInstance = (function () {
  let instance;
  return function () {
    if (!instance) {
      instance = new SingleObject();
    }
    return instance;
  };
})();

// test
// 注意⚠️这里使用静态函数 getInstance, 不能 new SingleObject();

let obj1 = SingleObject.getInstance();
obj1.login();
let obj2 = SingleObject.getInstance();
obj2.login();
console.log("obj1 === obj2 ", obj1 === obj2);

console.log("--------Divider----------");

let obj3 = new SingleObject();
obj3.login();
console.log("obj1 === obj3", obj1 === obj3);
weikee94 commented 11 months ago
class LoginForm {
    private state: string = 'hide' // 'hide' / 'show'

    private constructor() {}

    show() {
        if (this.state === 'show') {
            console.log('已经显示了')
            return
        }
        console.log('显示 LoginForm')
        this.state = 'show'
    }

    hide() {
        if (this.state === 'hide') {
            console.log('已经隐藏了')
            return
        }
        console.log('隐藏 LoginForm')
        this.state = 'hide'
    }

    private static instance: LoginForm | null = null
    static getInstance(): LoginForm {
        // 注意这里的 this
        if (this.instance == null) this.instance = new LoginForm()
        return this.instance
    }
}

const loginForm1 = LoginForm.getInstance()
const loginForm2 = LoginForm.getInstance()
weikee94 commented 11 months ago

常见使用地方 自定义事件 eventBus 全局只有一个 Vuex Redux store 全局只有一个

weikee94 commented 11 months ago
let instance;
class DBConnection {
  constructor(uri) {
    if(instance) {
      throw new Error('You can only create one single DB connection!');
    }
    this.uri = uri;
    instance = this;
  }

  connect() {
    console.log(`DB ${this.uri} has been connected!`);
  }

  disconnect() {
    console.log('DB disconnected');
  }
}

const connection = Object.freeze(new DBConnection('mongodb://...'));
export default connection;

stackblitz

Screenshot 2023-09-19 at 11 26 26 AM

from what we see the output is 4 is because we import file1 we also import singleton modules we didn't declare the actual singleton here but the actual output become 4