常用的四种设计模式

单例模式

一个构造函数一生只能有一个实例

function Person(){
	this.name='Jack'
}
//核心代码
let instance=null
function(){
 	if(!instance) instance=new Person()
	return instance
}
const p1=singleTon()
const p2=singleTon()
//改造单例模式
const Person(function(){
	function(name,age,gender){
		this.name=name
		this.age=age
		this.gender=gender
	}
	Person.prototype.sayHi=function(){console.log('hello world')}
	return function singleTon(...arg){
		let instance=null
		if(!instance){ instance=new Person}
		return instance
	}	
})()
const p1=new Person()
const p2=new Person()

观察者

class Observer{
	constructor(name,fn=()=>{}){
		this.name=name
		this.fn=fn
	}
}
const bzr=new Observer('班主任'()=>{console.log('把你爸找来')})
const xz=new Observer('校长'()=>{console.log('骂你的班主任')})
class subject{
	constructor(state){
		this.state=state
		this.observers=[]
	}
	setState(val){
		this.state=val
		this.observer.forEach(item=>{
			item.fn(this.state)
		})
	}
	addObserver(obs){
		this.observers=this.observers.filter(item=>item!==obs)
		this.observers.push(obs)
	}
}

发布订阅者模式

class Observer{
	constructor(){
		this.message={}
	}	
	//向队列里添加消息
	on(type,fn){
		if(!this.message[type]){
			this.message[type]=[]
		}
		this.message[type].push(fn)
	}
	//删除消息队列里的消息
	off(){
		if(!fn){
		delete this.message[type]
		return
		}
		if(!this.message[]type]) return
		this.message[type]=this.message[type].filter(item=>item!==fn)
	}
	//触发消息队列
	trigger(){
		if(!this.message[type]) return
		this.message[type].forEach(item=>{
			item()
		})
	}
}
const person1=new Observer()

策略模式

一个问题匹配多种方案,随时可以增加
利用闭包,使策略不会被销毁

const calcPrice=(function(){
	const sale={
		'100_30':function(price){return price-=10},
		'200_25':function(price){return price-=25},
		'80%':function(price){return price*=0.8}
	}
	function calcPrice(price,type){
		if(!sale[type]) return '没有这个折扣'
		return sale[type](price)
	}
	calcPrice.add=function(){
		if(sale[type]) return '该折扣已经存在'
		sale[type]=fn
	}
	calePrice.del=function(){
		delete this[type]
	}
	return calcPrice
})()
const res =calcPrice(320,'100_10')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值