这世界,纷纷绕绕,总是如此。
JavaScript设计模式样例二十一 —— 解释器模式
解释器模式(Interpreter Pattern)
|
1 2 3 |
定义:提供了评估语言的语法或表达式的方式。 目的:对于一些固定文法构建一个解释句子的解释器。 场景:编译器、运算表达式计算。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// 基础表达式:判断是否包含关键词 class Keyword { constructor(word) { this.word = word } interpret(context) { return context.includes(this.word) } } // 或表达式:满足任意一个条件 class Or { constructor(left, right) { this.left = left this.right = right } interpret(context) { return this.left.interpret(context) || this.right.interpret(context) } } // 与表达式:必须同时满足两个条件 class And { constructor(left, right) { this.left = left this.right = right } interpret(context) { return this.left.interpret(context) && this.right.interpret(context) } } // 构建规则:(John OR Robert) AND Married const rule = new And( new Or( new Keyword('John'), new Keyword('Robert') ), new Keyword('Married') ) // 解释输入,得到结果 console.log(rule.interpret('John Married')) // true console.log(rule.interpret('Robert Married')) // true console.log(rule.interpret('John')) // false console.log(rule.interpret('Julie Married')) // false |
JavaScript设计模式样例二十 —— 中介者模式
中介者模式(Mediator Pattern)
|
1 2 3 |
定义:用来降低多个对象和类之间的通信复杂性。 目的:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 场景:MVC框架中的控制器C就是模型M和识图V的中介者。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
// 中介者:统一协调跑道 const tower = { currentPlane: null, requestLanding(plane) { if (this.currentPlane) { console.log(`${plane.name}:跑道被占用,请等待`) return } this.currentPlane = plane plane.land() }, releaseRunway(plane) { if (this.currentPlane === plane) { this.currentPlane = null } } } // 参与者:只与塔台通信,不直接联系其他飞机 class Plane { constructor(name, tower) { this.name = name this.tower = tower } requestLanding() { this.tower.requestLanding(this) } land() { console.log(`${this.name}:开始降落`) } leaveRunway() { this.tower.releaseRunway(this) } } const planeA = new Plane('飞机A', tower) const planeB = new Plane('飞机B', tower) planeA.requestLanding() // 飞机A:开始降落 planeB.requestLanding() // 飞机B:跑道被占用,请等待 planeA.leaveRunway() planeB.requestLanding() // 飞机B:开始降落 |
Github地址:https://github.com/skillnull/Design-Mode-Example[……]
JavaScript设计模式样例十九 —— 职责链模式
职责链模式(Chain of Responsibility Pattern)
|
1 2 3 |
定义:为请求创建了一个接收者对象的链。 目的:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。 场景:红楼梦中的"击鼓传花"。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Approver { constructor(name, limit) { this.name = name this.limit = limit this.next = null } processRequest(request) { // 自己能处理,就处理并结束 if (request.amount < this.limit) { console.log(`${this.name}批准采购:${request.productName}`) return } // 自己不能处理,交给下一级 if (this.next) { return this.next.processRequest(request) } // 已经到达链尾,仍然无法处理 console.log(`采购金额超出审批权限:${request.productName}`) } } // 创建审批者 const manager = new Approver('经理', 10000) const vicePresident = new Approver('副总', 25000) const president = new Approver('总经理', 100000) // 连接职责链:经理 → 副总 → 总经理 manager.next = vicePresident vicePresident.next = president // 所有请求都从链头提交 manager.processRequest({ amount: 4000, productName: '电话' }) manager.processRequest({ amount: 10000, productName: '软件' }) manager.processRequest({ amount: 40000, productName: '电脑' }) manager.processRequest({ amount: 200000, productName: '服务器' }) |
输出:
经理批准采购:电话
副总批准采购:软件
总经理批准采购:电脑
采[……]
JavaScript设计模式样例十八 —— 命令模式
命令模式(Command Pattern)
|
1 2 3 |
定义:请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。 目的:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。 场景:在一个快餐店,用户向服务员点餐。服务员将用户的需求记录在清单上。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 1. 接收者:真正做事 const light = { turnOn() { console.log('灯亮了') } } // 2. 命令:封装“让这盏灯打开”的请求 class TurnOnCommand { constructor(light) { this.light = light } execute() { this.light.turnOn() } } // 3. 调用者:只负责执行命令 const remote = { press(command) { command.execute() } } // 使用 const command = new TurnOnCommand(light) remote.press(command) // 灯亮了 |
JavaScript设计模式样例十七 —— 迭代器模式
迭代器模式(Itrator Pattern)
|
1 2 3 |
定义:用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 目的:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。 场景:$.each() for..of。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function each(iterable, callback) { if (iterable == null || typeof iterable[Symbol.iterator] !== 'function') { throw new TypeError('第一个参数必须是可迭代对象') } if (typeof callback !== 'function') { throw new TypeError('callback 必须是函数') } let index = 0 for (const value of iterable) { if (callback(index, value, iterable) === false) { break } index++ } return iterable } // 使用: each(new Set(['a', 'b', 'c']), (index, value) => { console.log(index, value) }) // 输出: 0 a 1 b 2 c |
JavaScript设计模式样例十六 —— 备忘录模式
备忘录模式(Memento Pattern)
|
1 2 3 |
定义:保存一个对象的某个状态,以便在适当的时候恢复对象。 目的:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。 场景:数据缓存。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function createPageCache() { const cache = new Map() return async function getPageData(page, loader) { if (cache.has(page)) { return cache.get(page) } const data = await loader(page) cache.set(page, data) return data } } const getPageData = createPageCache() // 使用: async function fetchPageData(page) { console.log(`请求第 ${page} 页数据`) return { page, list: ['数据1', '数据2'] } } const data1 = await getPageData(1, fetchPageData) const data2 = await getPageData(1, fetchPageData) console.log(data1) console.log(data2) |
JavaScript设计模式样例十五 —— 状态模式
状态模式(State Pattern)
|
1 2 3 4 |
定义:创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。 目的:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。 场景:游戏角色有跳跃、移动、射击、蹲下等状态设定,如果用if-else或者switch来进行判断, 在遇到组合动作的时候,判断会变得非常复杂难读,这时可以使用状态模式来实现。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
const stateTable = { standing: { move: { message: '英雄开始移动' }, jump: { message: '英雄跳了起来', next: 'jumping' }, squat: { message: '英雄蹲下', next: 'squatting' }, shoot: { message: '英雄站立射击' } }, jumping: { move: { message: '英雄在空中调整方向' }, jump: { message: '英雄已经在空中,不能再次跳跃' }, squat: { message: '英雄在空中,不能蹲下' }, shoot: { message: '英雄在空中射击' }, land: { message: '英雄落地', next: 'standing' } }, squatting: { move: { message: '英雄蹲着缓慢移动' }, jump: { message: '英雄从蹲下状态起跳', next: 'jumping' }, squat: { message: '英雄已经蹲下' }, shoot: { message: '英雄蹲下射击' }, stand: { message: '英雄站了起来', next: 'standing' } } } class SuperHero { #state = 'standing' get state() { return this.#state } action(actionName) { const rule = stateTable[this.#state]?.[actionName] if (!rule) { console.log(`${this.#state} 状态不支持 ${actionName} 动作`) return this } console.log(rule.message) this.#state = rule.next ?? this.#state return this } } // 使用: const hero = new SuperHero() hero .action('move') .action('jump') .action('jump') .action('shoot') .action('land') .action('squat') .action('move') console.log(hero.state) // squatting // 输出: 英雄开始移动 英雄跳了起来 英雄已经在空中,不能再次跳跃 英雄在空中射击 英雄落地 英雄蹲下 英雄蹲着缓慢移动 |
JavaScript设计模式样例十四 —— 观察者模式
观察者模式(Observer Pattern)
|
1 2 3 |
定义:当一个对象被修改时,则会自动通知它的依赖对象。 目的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 场景:一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知,进行广播通知。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
class Subject { #state = 0 #observers = new Set() getState() { return this.#state } setState(state) { if (Object.is(this.#state, state)) { return } const previousState = this.#state this.#state = state this.notifyAllObservers({ previousState, currentState: state }) } attach(observer) { if (typeof observer?.update !== 'function') { throw new TypeError('观察者必须提供 update() 方法') } this.#observers.add(observer) // 返回取消订阅函数 return () => { this.detach(observer) } } detach(observer) { return this.#observers.delete(observer) } notifyAllObservers(change) { // 使用快照,避免通知期间修改集合影响当前遍历 const observers = [...this.#observers] for (const observer of observers) { observer.update(this, change) } } } // 观察者: class Observer { constructor(name, subject) { this.name = name this.unsubscribe = subject.attach(this) } update(subject, change) { console.log( `${this.name}:`, change.previousState, '→', change.currentState ) console.log('当前状态:', subject.getState()) } dispose() { this.unsubscribe() } } // 使用: const subject = new Subject() const observer1 = new Observer('observer 1', subject) const observer2 = new Observer('observer 2', subject) subject.setState('hahaha') |
Github地址:https://github.com/skillnull/Design-Mode-Example[……]
JavaScript设计模式样例十三 —— 模版方法模式
模板方法模式(Template Method Pattern)
|
1 2 3 |
定义:一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。 目的:一些方法通用,却在每一个子类都重新写了这一方法。 场景:在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Beverage { // 公共步骤 boilWater() { console.log('烧水') } // 要求子类实现的可变步骤 brew() { throw new Error('子类必须实现 brew() 方法') } // 模板方法 prepare() { this.boilWater() this.brew() } } class Tea extends Beverage { brew() { console.log('头杯茶不喝,喝第三杯') } } const tea = new Tea() tea.prepare() |