关于前端:5设计模式之装饰模式

2次阅读

共计 1354 个字符,预计需要花费 4 分钟才能阅读完成。

装璜模式:动静地给一个对象增加一些额定的指摘,就减少性能来说,装璜模式比生成子类更加灵便

「装璜模式」对于前端开发者而言肯定是十分相熟的,什么是「装璜模式」呢?顾名思义,「装璜模式」就像是给一个类穿上一件一件衣服,通过不同的搭配,让这个类呈现出不同的特点。那咱们在工作的过程中,在编写页面的时候,做的如同也是一样的事件对吧?比方按钮组件,他会有 defaultprimaryhoveractivedisabled 等等状态,咱们罕用的形式就是通过给 button 增加不同的 class 来实现这种种不同的成果,其实这种实现的形式,就是「装璜模式」的利用。只不过明天咱们说的是「装璜模式」在 JS 中的利用而已,咱们能够通过 CSS 的思维来帮忙咱们了解。

实例:当下咱们须要做一套考试零碎,一套试卷由一道道试题组成,试题会有练习、考试和解析 3 种状态:

  • 练习状态下,试题须要显示题干和选项
  • 考试状态下,试题须要显示题干、选项和分数
  • 解析状态下,题干须要显示题干、选项、分数和解析

由上咱们能够设想出具体的实现模式就是依据源数据在不同条件下显示不同的状态和内容,就能够联合「装璜模式」来实现。

// 试题渲染
class Question {constructor(question) {this.question = question;}
 
 render() {console.log(this.question.topic);
 console.log(this.question.options);
 }
}
​
// 分数渲染装璜器
class ScoreQuestion {constructor(question) {this.question = question;}
 
 render() {this.question.render();
 console.log(this.question.question.score);
 }
}
​
// 解析渲染装璜器
class AnalyzeQuestion {constructor(question) {this.question = question;}
 
 render() {this.question.render();
 console.log(this.question.question.analyse);
 }
}
​
const question = {
 topic: '题干',
 options: '选项一、选项二、选项三',
 score: 10,
 analyse: '选项一是正确答案'
};
​
let instance = new Question(question);
instance.render();
// 题干
// 选项一、选项二、选项三
​
instance = new ScoreQuestion(instance);
instance.render();
// 题干
// 选项一、选项二、选项三
// 10
​
instance = new AnalyzeQuestion(instance);
instance.render();
// 题干
// 选项一、选项二、选项三
// 10
// 选项一是正确答案

总结

如果咱们实现一项性能能够做到将外围指摘与装璜性能辨别的话,就能够应用「装璜模式」来实现。「装璜模式」的长处就在于 把类中的装璜性能从类中搬移去除,这样能够简化原有的类


参考

大话设计模式 — 程杰

集体博客

北落师门的博客

正文完
 0