js设计模式(一)

137 阅读1分钟

1.单例模式

只获得唯一一个对象,通过单例模式可以保证系统中,应用该模式的一个类只有一个实例 有多种实现方式

const ProxyCreateSingleton = (function(fn){
	let instance
    return  function(age){
      if(instance) return instance
      return instance = new fn(...arguments)
	}
})(Per)
function Per(name,age){
	this.name = name
    this.age = age
}
p=new ProxyCreateSingleton('哦',11)

工厂模式

工厂模式是一种用来创建对象的设计模式。我们不暴露对象创建的逻辑,而是将逻辑封装在一个函数内,那么这个函数可以成为工厂。

function Factory(opts){
    let obj={
    	color:opts.color,
        name:opts.name
    }
    obj.getInfo = function(){
        return '名称:'+ obj.name+', 颜色:'+ obj.color;
    }
    return obj;
}
let phone = new Factory('手机','黑色')
phone.getInfo()//"名称:手机, 颜色:黑色"

订阅发布模式

支持简单的广播通信,当对象状态发生改变时,会自动通知已经订阅过的对象 发布订阅模式与观察者模式非常接近,仅仅只是多了一个中间层用于管理消息(信息通道),可以看成是一种优化的观察者模式。 eventList为管理消息通过add添加监听事件 emit时将触发对应的监听事件

function Publisher(){
this.eventList={}
}
Publisher.prototype={
	add:function(type, handle){
		if(!this.eventList[type]){
			this.eventList[type] = [];
		}
		this.eventList[type].push(handle)
	},
 	emit:function(){
		const type = Array.prototype.shift.call(arguments)
		if(this.eventList[type]){
			this.eventList[type].forEach((handle)=>{
				handle.apply(this, arguments)
			})
		}
	},
	remove: function (type, handle) {
		let handles = this.eventList[type]
		if(handles){
			if(!handle){
				handles.length = 0
			}else{
				const index = handles.findIndex((_handle)=>handle!=_handle)
				if(index>=0){handles.splice(i,1)};
			}
		}
	}
}


let p = new Pubsub();
p.add('num',(a)=>{console.log(a)}
p.add('num',(a)=>{console.log(a+1)}
p.emit('num',1)
p.remove('num',(a)=>{console.log(a+1))
p.emit('num',1)

目录