单例模式
一个构造函数一生只能有一个实例
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')