js设计模式

单例模式

(单体模式提供了一种将代码组织为一个逻辑单元的手段,这个逻辑单元中的代码可以通过单一变量进行访问)

let obj = {
  name: 'xx',
  age: 20
}

工厂模式

(工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式,就是同样形式参数返回不同的实例)

function Person() { this.name = 'Person1'; }
function Animal() { this.name = 'Animal1'; }

function Factory() {}
Factory.prototype.getInstance = function(className) {
  return eval('new ' + className + '()');
}

var factory = new Factory();
var obj1 = factory.getInstance('Person');
var obj2 = factory.getInstance('Animal');
console.log(obj1.name); // Person1
console.log(obj2.name); // Animal1

代理模式

(为其他对象提供一种代理以控制对这个对象的访问)

function Person() { }
Person.prototype.sayName = function() { console.log('michaelqin'); }
Person.prototype.sayAge = function() { console.log(30); }

function PersonProxy() { 
  this.person = new Person();
  const that = this;
  this.callMethod = function(functionName) {
    console.log('before proxy:', functionName);
    that.person[functionName](); // 代理
    console.log('after proxy:', functionName);
  }
}

var pp = new PersonProxy();
pp.callMethod('sayName'); // 代理调用Person的方法sayName()
pp.callMethod('sayAge'); // 代理调用Person的方法sayAge()    

观察者模式

function Publisher() {
  this.listeners = [];
}
Publisher.prototype = {
  addListener(listener){
    this.listeners.push(listener);
  },
  removeListener(listener){
    delete this.listeners[listener];
  },
  notify(obj){
    this.listeners.forEach(listener => {
      if(typeof listener !== 'undefined'){
        listener.process(obj);
      }
    })
  }
}
function Subscriber() {
  
}
Subscriber.prototype = {
  process(obj){
    console.log(obj)
  }
}

const p = new Publisher();
原文地址:https://www.cnblogs.com/colima/p/8687123.html