说到设计模式,其实觉得自己有很多要学的东西,但是,自己看了设计模式相关的书籍,看书的时候看得津津有味,明明白白,但是一到自己写代码的时候,又写得磕磕巴巴,也想不到自己要用哪种设计模式,有种阅后即焚的感觉,所以设计模式这种东西还是得一个个掰开了慢慢看,边看边学习。
策略模式
定义:
定义一系列的算法,把它们一个个封装起来,并且使它们可以互相替换
例子如下:
// 旧的方法
var calculateBonus = function(performancelevel, salary) {
if(performancelevel === 'S'){
return salary * 4
}
if(performancelevel === 'A'){
return salary * 3
}
if(performancelevel === 'B'){
return salary * 2
}
}
calculateBonus('B', 20000)
// 使用策略模式后
const perforamnceS = function(salary) {
return salary * 4
}
const performanceA = function(salary){
return salary * 3
}
const performanceB = function(salary){
return salary * 2
}
const calculateBonus = function(performanceLevel, salary){
if(performanceLevel === 'S'){
return perforamnceS(salary)
}
if(performanceLevel === 'A'){
return perforamnceA(salary)
}
if(performanceLevel === 'B'){
return perforamnceB(salary)
}
}
calculateBonus('A', 10000)
使用场景:
- 各种判断条件下的策略相互独立且可复用
- 策略内部逻辑相对灵活
- 策略需要灵活组合
发布订阅模式
发布订阅是一个老生常谈的设计模式,特别是在前端中,提到vue的响应式的原理就会提到发布订阅模式,antd-react的源码里面也用到了发布订阅模式
这个就不写例子了,需要记住的是一个这样的图,用图来表示更加清晰
使用场景:
- 各模块相互独立
- 存在一对多的依赖关系
- 依赖模块不稳定、依赖关系不稳定
- 各模块由不同的人员、团队开发
装饰器模式和适配器模式
定义:
装饰器模式:动态的给某个对象添加一些额外的职责,而不会影响从这个类中派生的其他对象
适配器模式:让两个或多个原本不可以一起工作的对象可以一起工作
## 装饰器模式
let Plane = function(){}
Plane.prototype.fire = function(){
console.log('发射普通子弹')
}
const MissileDecorator = function(plane) {
this.plane = plane
}
MissileDecorator.prototype.fire = function(){
this.plane.fire()
console.log('发射导弹')
}
const AtomDecorator = function(plan){
this.plane = plane
}
AtomDecorator.prototype.fire = function(){
this.plane.fire()
console.log('发射原子弹')
}
let plane = new Plane()
plane = new MissileDecorator(plane)
plane = new AtomDecorator(plane)
plane.fire()
// 适配器模式
const googleMap = {
show: function() {
console.log('开始渲染谷歌地图')
}
}
const baiduMap = {
show: function(){
console.log('开始渲染百度地图')
}
}
const renderMap = function(map){
if(map.show instanceof Function){
map.show()
}
}
renderMap(googleMap)
renderMap(baiduMap)
// 使用适配器之后
const gooleMap = {
show:function(){
console.log('开始渲染谷歌地图')
}
}
const baiduMap = {
display: function(){
console.log('开始渲染百度地图')
}
}
const baiduMapAdapter = {
show: function(){
return baiduMap.display()
}
}
renderMap(gooleMap)
renderMap(baiduMapAdapter)
使用场景:
- 高阶函数
- 适配
代理模式
定义
为一个对象提供一个占用品或占位符,以便控制对它的访问