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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值