前言
在开发中我们经常会有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护的问题,导致了代码逻辑复杂,添加新功能难以维护等。在最近的学习与工作过程中,我也使用到了策略模式优化代码,希望可以通过学习让自己的技术不断提升。
策略模式
定义
定义一系列算法,并将他们分别封装,使得它们可以互相替换
使用场景
一个系统需要动态地在几种算法中选择一种 如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现
下面将通过简单用法以及我在工作中优化的内容来举🌰
计算器
function getNum(type, a, b) {
if (type == 'add') {
return a + b
}
if (type == 'sub') {
return a - b
}
}
-
在计算器这个例子中,我们可以发现当需要添加除法,乘法等功能的时候,就需要不断地添加if来实现,那如果使用策略模式来书写呢?
class Strategies {
add(a, b) {
return a + b
}
sub(a, b) {
return a - b
}
}
const strategies = new Strategies()
function strategiesFn(type, a, b) {
return strategies[type](a, b)
}
-
使用策略模式,每种功能都是一个独立的方法,这样就替换了if else带来的代码可读性差的问题
下面是我在项目中运用策略模式的🌰
-
功能:tab切换时,切换到三个不同的组件
//template
<div class="tab_container">
<div class="tab_item" @click="changeTab(index,item.type)" v-for="(item,index) in tabList" :key="index">
<span>{{item.tabName}}</span>
<div :class="currentIndex == index ?'tab_decorate':''" ></div>
</div>
</div>
<component :is="componentTab"></component>
//script
components: {
BasicMsg,//基本信息组件
historyAnnounce,//历史公告组件
followUp//跟进纪录组件
},
data () {
return {
currentIndex:0
componentTab: BasicMsg,
tabType: 'basic',
tabList: [
{ tabName: '基本信息', type: 'basic' },
{ tabName: '历史公告', type: 'history' },
{ tabName: '跟进记录', type: 'follow' }]
}
},
methods: {
//切换tab的事件
changeTab (type) {
this.currentIndex = index
this.tabType = type
const componentObj = {
basic: function () {
return BasicMsg
},
history: function () {
return historyAnnounce
},
follow: function () {
return followUp
}
}
this.componentTab = componentObj[type]()
}
},
总结:在上面举得实际开发中的例子中仅切换tab,其实也可以直接用if else 来实现,但是如果后续需要在切换的时候继续做点什么事呢?if else就会使得代码变得难读,体量变大。在开发中,有时不需要使用策略模式也可以很好的解决问题,但是考虑到项目都是不断更新迭代的,因此代码也需要一定的健壮性,而设计模式就是使代码健壮性变强的格式或套路,希望可以在自己开发的过程中更好的运用设计模式。
注:学习系列为学习过程与工作实践中总结的内容,希望自己可以写出更多更好的文章~
本文由 mdnice 多平台发布