2

简化理解:策略设计模式_安东尼漫长的技术岁月的技术博客_51CTO博客

 2 years ago
source link: https://blog.51cto.com/u_13961087/5558257
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

简化理解:策略设计模式

推荐 原创

掘金安东尼 2022-08-09 11:12:50 ©著作权

文章标签 设计模式 策略模式 开闭原则 文章分类 JavaScript 前端开发 阅读数219

就在前不久,我们讲了创建对象的 3 种常见设计模式:工厂设计模式、构造函数设计模式、原型设计模式。这 3 种设计模式,真切时刻发生在我们日常编码生活中,蓦然回首,灯火阑珊处。

本篇带来另外一种设计模式介绍,你或许天天和它打交道,但是不认识它,它就是“策略模式”。

策略模式就像诸葛亮的锦囊,它在代码中是这样体现的:

比方说,我们有一个销售活动,它有着不同的销售策略

function getPrice(originalPrice, status) {
if (status === 'pre-sale') { // 预售打 8 折
return originalPrice * 0.8
}

if (status === 'promotion') { // 促销打 9 折或者便宜 20
if (origialPrice <= 100) {
return origialPrice * 0.9
} else {
return originalPrice - 20
}
}

if (status === 'black-friday') { // 周五有多种打折策略
if (origialPrice >= 100 && originalPrice < 200) {
return origialPrice - 20
} else if (originalPrice >= 200) {
return originalPrice - 50
} else {
return originalPrice * 0.8
}
}

if (status === 'default') { // 默认不打折
return originalPrice
}
}

这样写,有无毛病?

老观众都知道:当然是有的,它违反了“开闭原则”和“单一职责原则”。(这两个原则经常提到,敲重点)

为啥违反“开闭原则”?因为当你要加入一个新的策略的时候,要修改 getPrice 函数内部代码,这不是我们提倡的,我们提倡:不频繁修改函数体内部,通过预留的扩展接口来增加功能;

即:修改函数内部 ⇒ no,拓展函数功能 ⇒ yes

为啥违法“单一职责”?因为 getPrice 函数负责的判断太多了,又是这又是那的,职责太多,都没有解耦;

还有一个更大的问题,当其中的一种策略代码报错,会影响到整个 getPrice 函数的向下执行。

基于以上的原因,于是乎,策略模式闪亮登场!!

function preSalePrice(origialPrice) { // 预售打 8 折
return originalPrice * 0.8
}

function promotionPrice(origialPrice) { // 促销打 9 折或者便宜 20
if (origialPrice <= 100) {
return origialPrice * 0.9
} else {
return originalPrice - 20
}
}

function blackFridayPrice(origialPrice) { // 周五有多种打折策略
if (origialPrice >= 100 && originalPrice < 200) {
return origialPrice - 20
} else if (originalPrice >= 200) {
return originalPrice - 50
} else {
return originalPrice * 0.8
}
}

function defaultPrice(origialPrice) { // 默认不打折
return origialPrice
}

let priceStrategies = { // 打折策略
'pre-sale': preSalePrice,
'promotion': promotionPrice,
'black-friday': blackFridayPrice,
'default': defaultPrice
}

function getPrice(originalPrice, status) { // 根据策略获取价格
return priceStrategies[status](originalPrice)
}

优化后,代码从这样:

简化理解:策略设计模式_设计模式

变成了这样:

简化理解:策略设计模式_开闭原则_02

 ​图片来源​

完美解决!!代码看起来更简洁、清晰。

如果你的代码有很多 if…else… 判断,各判断里的代码又相互独立,可考虑使用策略模式,封装各判断的代码,用 map 的方式,取出你的锦囊妙计吧

策略模式,就这,原来设计模式就在我们身边~~

参考:​ ​useful-design-patterns​

作者:​ ​bytefish​

OK,以上便是本篇分享。点赞关注评论,为好文助力👍

我是掘金安东尼 🤠 100 万阅读量人气前端技术博主 💥 INFP 写作人格坚持 1000 日更文 ✍ 关注我,陪你一起度过漫长编程岁月 🌏


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK