前端设计模式学习

23种设计模式

在这里插入图片描述

设计模式是什么

设计模式是前人遇到大量相似逻辑,而研究出的一种最有效的编程方法。简单来说,设计模式是用来解决某些逻辑业务的。

为什么要学习设计模式

学好设计模式,等你遇到了那些逻辑业务时,就能用超有效的代码去解决这些逻辑业务。后端常用的设计模式有23种,而前端常用的不到十种。所以作为前端工程师,只要掌握这几种就够了。

前端常用的设计模式(*为最核心)

  1. 工厂模式 *
  2. 单例模式 *
  3. 观察者模式 *
  4. 命令模式
  5. 模板模式
  6. 策略模式
  7. 命名空间模式
  8. 备忘录模式
  9. 装饰器模式

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
}
// 太复杂,不推荐

3.观察者模式

https://www.bilibili.com/video/BV1Rb411K7xs?p=58 0:40

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值