ES5
function Person() {
if (!Person._instance) {
this.name = "姓名";
Person._instance = this;
}
return Person._instance;
}
const p1 = new Person();
const p2 = new Person();
console.log(p1 === p2);
ES6
class Person {
constructor() {
if (!Person._instance) {
this.name = "姓名";
Person._instance = this;
}
return Person._instance;
}
}
const p1 = new Person();
const p2 = new Person();
console.log(p1 === p2);
单例模式的高阶函数
function Person() {
this.name = "姓名";
}
function SingleWrapper<T>(Constructor: T): T {
if (!(Constructor instanceof Function) || !Constructor.prototype) {
throw new Error("不是合法的构造函数");
}
let instance;
return function (...args) {
if (!instance) {
instance = new Constructor(...args);
}
return instance;
};
}
const SinglePerson = SingleWrapper(Person);
const p1 = SinglePerson();
const p2 = SinglePerson();
console.log(p1 === p2);