You're never really done for, as long as you‘ve got a good story and someone to tell it to.

Javascript设计模式

设计模式

1. 单例模式

ES6普通单例

缺点: 不能使用new关键字, 必须要通过getInstance方法
优点: 创建简单

class Person {
 constructor(name) {
  this.name = name;
 }

 static getInstance(name) {
  return this.instance || (this.instance = new Person(name));
 }
}
const a = Person.getInstance("lee");
const b = Person.getInstance("lisa");
console.log(a === b, a.name, b.name);

ES5普通单例

缺点: 不能使用new关键字, 必须要通过getInstance方法
优点: 创建简单

function Person(name) {
 this.name = name;
}
Person.getInstance = (function() {
 let instance;
 return function(name) {
  return instance || (instance = new Person(name));
 };
})();
const a = Person.getInstance("lee");
const b = Person.getInstance("lisa");
console.log(a === b, a.name, b.name);

透明单例

缺点: 违反单一原则
优点: 可以使用new关键字

const Person = (function() {
 let instance;
 return function(name) {
  if (instance) {
   return instance;
  } else {
   this.name = name;
   return (instance = this);
  }
 };
})();

const a = new Person("lee");
const b = new Person("lisa");
console.log(a === b, a.name, b.name); // true 'lee' 'lee'

代理单例

缺点:不够灵活
优点:可以使用new关键字, 符合单一原则

function Person(name) {
 console.l;
 this.name = name;
}

const createSingleton = (function() {
 let instance;
 return function(name) {
  return instance || (instance = new Person(name));
 };
})();

const a = new createSingleton("lee");
const b = new createSingleton("lisa");
console.log(a === b, a.name, b.name);

单例封装

优点: createSingleton方法成为共用方法, 使用new关键字没有影响

const createSingleton = (fn) => {
 let instance;
 return function() {
  return instance || (instance = new fn(...arguments));
 };
};

const Person = function(name) {
 this.name = name;
};
Person.prototype.getName = function() {
 console.log(this.name);
};
const personSingleton = createSingleton(Person);
const a = new personSingleton("lisa");
const b = new personSingleton("lee");
a.getName();
b.getName();
console.log(a === b, a.name, b.name);
# 设计模式  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×