23种设计模式
设计模式是什么
设计模式是前人遇到大量相似逻辑,而研究出的一种最有效的编程方法。简单来说,设计模式是用来解决某些逻辑业务的。
为什么要学习设计模式
学好设计模式,等你遇到了那些逻辑业务时,就能用超有效的代码去解决这些逻辑业务。后端常用的设计模式有23种,而前端常用的不到十种。所以作为前端工程师,只要掌握这几种就够了。
前端常用的设计模式(*为最核心)
- 工厂模式 *
- 单例模式 *
- 观察者模式 *
- 命令模式
- 模板模式
- 策略模式
- 命名空间模式
- 备忘录模式
- 装饰器模式
1.工厂模式
复杂工厂设计模式可用于token的存储,因为有些浏览器支持localstorage,有些浏览器不支持,得用cookie。
// 简单工厂设计模式 —— 咖啡机
function makeCoffee(bean, water) {
let obj = new Object()
obj.bean = bean
obj.water = water
obj.percentage = bean / water
// obj.xxx = xxx等code
return obj
}
/*
使用不同原料,产生属性一样,属性值多样的产品(同类型)就叫简单工厂设计模式
*/
复杂工厂设计模式 https://www.bilibili.com/video/BV1Rb411K7xs?p=57
// 复杂工厂设计模式 —— 果汁工厂
function FruitMaker() {}
FruitMaker.prototype.make = function(type, meta) {
// 判断工厂是否有能力生产该type
if (typeof this[type] === 'function') {
let fun = this[type]
fun.prototype = FruitMaker.prototype
return new fun(meta)
}
else {
throw '工厂不支持生产该商品'
}
}
FruitMaker.prototype.extend = function(obj) {
for (const fruitName in obj) {
this[fruitName] = obj[fruitName]
}
}
FruitMaker.extend({
apple: function(meta) {
console.log('制造了apple, 材料有', meta)
}
pear: function(meta) {
console.log('制造了pear, 材料有', meta)
}
})
const fm = new FruitMaker()
fm.make('apple', '一个苹果,一斤水')
fm.extend
/*
使用不同原料,产生不同类型的产品(属性多样,属性值多样),就叫复杂工厂设计模式
*/
2.单例模式
无论new多少次,都只返回同一个对象,就叫单例模式。
比如登录注册就可以用单例。
单例模式的实现方法:全局变量,静态属性,即时函数,闭包-惰性函数等…
// 全局变量实现单例
let instance = null;
function Instance() {
if(instance) return instance
instance = this
// this.xxx = xxx等code
}
// 但全局变量会污染全局,静态属性也可以被修改,所以这两种都不太给力
// 即时函数
let Instance = (function() {
let instance = null
return function() {
if(instance) return instance
instance = this
// this.xxx = xxx等code
}
})()
// 推荐使用这种方法
// 惰性函数(但缺点是用户不能在Instance原型上挂载属性)
function Instance() {
let instance = this
let oldPrototype = Instance.prototype
// this.xxx = xxx等code
Instance = function() {
return instance
}
Instance.prototype = oldPrototype // 防止原型丢失
instance = new Instance()
instance.constructor = Instance
}
// 不推荐
// 惰性函数(完美版)
function Instance() {
let instance = this
let oldPrototype = Instance.prototype
// this.xxx = xxx等code
Instance = function() {
return instance
}
Instance.prototype = oldPrototype // 防止原型丢失
instance = new Instance()
instance.constructor = Instance
return instance
}
// 太复杂,不推荐