设计模式
针对不同的问题提出的解决方案 每一种设计模式只是为了解决一个问题
常见的设计模式
- 工厂模式
- 单例模式 : 针对构造函数创建出来的实例化对象的代码一模一样,形成的一种解决方案
- 组合模式
- 观察模式
- 策略模式
- 代理模式
工厂模式
//工厂函数
function Person(){
const obj = {}
obj.name = "张三"
obj.age = 20
return obj
}
//工厂模式
function factory(){
function SuperAdmin(){
this.name = "超级管理员"
this.age = 80
this.jurisdition = ['首页','列表页','注册','登录','管理','系统设置']
}
function Admin(){
this.name = "管理员"
this.age = 50
this.jurisdition = ['首页','列表页','注册','登录','管理']
}
function User(){
this.name = "用户"
this.age = 20
this.jurisdition = ['首页','列表页','注册','登录']
}
switch(role){
case "superAdmin":
return new SuperAdmin()
break
case "admin":
return new Admin()
break
case "user":
return new User()
break
}
}
const res = factory("user")
console.log(res)
单例模式
针对构造函数创建出来的实例化对象 代码一模一样,形成的一种解决方法
function Apple(){
this.name = "苹果"
this.eat = "好吃"
}
Apple.prototype.zhazhier = function(){
console.log("好喝")
}
const a1 = new Apple()
const a2 = new Apple()
console.log(a1)
console.log(a2)
console.log(a1 === a2) // false 单例模式实现最终结果为true
function Fn(){
const obj={}
return obj
}
const o1 = Fn()
const o2 = Fn()
console.log(o1 === o2) //false
let obj
function Fn(){
if(!obj){
obj = {}
}
return obj
}
//第一次执行代码 全局obj === undefined Fn() => 会进入if 判断 给obj赋值为一个函数的地址 return 出去
//第二次执行代码 全局obj ==={} 地址 Fn() => 不会进入 if 判断 直接return
const o1 = Fn()
const o2 = Fn()
console.log(o1 === o2) //true
//单例模式 构造函数一生只有一个实例化对象
let res
function Singleton(){
function Instance(){
this.name = "instance"
}
if(!res){
res = new Instance()
}
return res
}
const s1 = new Singleton()
const s2 = new Singleton()
console.log(s1 === s2) //true
组合模式和其他模式
class GoHome{
constructor(){
}
inita(){
console.log("go home")
}
}
class OpenComputer{
consttructor(){
}
init(){
console.log("open computer")
}
}
class PlayGame{
consttructor(){
}
init(){
console.log("play game")
}
}
/*
常规操作
const res1 = new GoHome()
console.log(res1)
const res2 = new OpenComputer()
console.log(res2)
const res3 = new PlayGame()
console.log(res3)
*/
//组合模式,把需要调用的放在一个数组里面
class Fn{
consttructor(){
this.event =[new GoHome(),new OpenComputer(),new PlayGame()]
}
init(){
//把上面的那些东西,全部加到数组去 //统一调用
this.event.forEach(item=>{
item.init()
})
}
}
const f1 = new Fn()
f1.init()
观察模式 (发布-订阅模式 / 消息模式) addEventLIstener
策略模式 根据不同条件返回不同的值