js设计模式

. js设计模式

市场上常用的设计模式
单例模式
组合模式
观察者模式
适配器模式
代理模式
工厂模式
构建模式等等
我来讲讲常用的3种。
1.单例模式
1.针对特定问题而给出的简洁优化处理方案。
2.只能针对特定问题,不能处理其他问题。
3.同一个问题在不同位置,不一定能用同一种方法解决。
用于让一个构造函数一辈子只有一个实验对象,如果使用单例模式,每次new都是创造一个对象,如果使用单例模式,每次new都是使用第一次的对象。
单例模式代码
Function Person(){
This.name=’alan’}
var instance = null
Function singleton(){
If instance =null{
Instance = new Person()
}
Return instance
}
Singleton 第一次调用的时候
If 条件判断, 判断 instance === null
现在自己作用域里面没有 instance, 去到 父级作用域访问
也就是拿到了 全局作用域的 instance
Var p1 = singleton()
Singleton 第二次调用的时候
If 条件判断, 判断 instance === null
现在自己作用域里面没有 instance, 去到 父级作用域访问
也就是拿到了 全局的 instance
Return instance 就是return上面的实例
Var p2 =singleton()
Console.log(p1
=p2)

2.组合模式
组合模式像一个总开关,总开关一动,我们做好的构造函数就一起启动了
组合模式需要:1.一个承载所有构造函数实例的数组 2.需要方法向数组中添加内容 3.需要方法将数组里面内容启动。
构造函数的启动方式
组合模式就像家里的电闸,电闸一开所有东西都有电可以运作了
Class play{
Constructor (){}
构造函数的启动方法
init( ){console.log(“开始”)
this.a
this.b
this.c}
a(){}
b(){}
c(){}
}
第二个构造函数
class Eat{
constructor(){}
init () {console.log(‘吃饭’)
}}
class Sleep {
constructor () {}
init () {
console.log(‘睡觉’)
}
}}
组合模式的代码
class Compose{
constructor(){
this.composeArr=[ ]
}
用来承载每个实例的数组
add(instance){
this.composeArr.push(instance)}
向数组内添加内容
init(){
console.log(‘总开关启动了’)
this.composeArr.forEach(item=>item.init())}
}
var c = new Compose()
c是一个总开关
c,add(new Play())
c.add(new Eat())
c.add(new Sleep())
c.init()
console.log©
总开关一起动所有东西都启动了

3.观察者模式
观察者模式有3个状态,订阅,取消订阅,发布,
需要消息盒子,订阅的方法,取消订阅的方法,发布时间的方法
就像是去买书,今天没有要买的书就第二天再来买,没有就第三天来,直到买到需要的书为止
class Observer{
constructor(){
this.message=()
}
准备的消息盒子

订阅的方法
on(type,fn){
if(!this.message[type]){
this.message[type]=[ ]}
this.message[type].push(fn)
}
取消订阅的方法
off(type,fn){
if(!this.message[type]) return
this.message[type]=this.message[type].filter(item=>item!==fn)
}
发布的方法
emit(type){
if(!this.message[type]) return
this.message[type].forEach(item=>item())
}
}
使用的时候
var o = new Observer()
订阅事件
o.on(‘click’,handlerA)
o.on(‘click’,handlerB)
取消订阅事件
o.off(‘click’,handlerA)
发布事件
console.log(o)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值