責(zé)任鏈模式 (Chain of Responsibility)
責(zé)任鏈模式的一個(gè)典型的NodeJS的例子就是Express中的Middleware模型。往往是一個(gè)請求或者數(shù)據(jù)對象需要經(jīng)過幾道工序或者需要從幾個(gè)handler中選擇一個(gè)handler來處理這個(gè)對象泉手。每個(gè)工序會(huì)對這個(gè)對象就行判斷或者在這道工序上終止操作黔寇,要么會(huì)傳遞到下一個(gè)handler。所以這個(gè)設(shè)計(jì)模式斩萌,要求每個(gè)handler需要致命下一個(gè)handler是什么缝裤。然后每個(gè)handler需要有個(gè)判斷條件,來判斷是否需要傳遞到下一個(gè)handler還是在這個(gè)handler就終止颊郎。
class Handler1 (){
constructor(next) {
this.next = next;
}
judge(obj) {
if (condition) {
// do something
} else if (this.next) {
this.next.judge(obj);
} else {
// Error Handering
}
}
}
class Handler2 (){
constructor(next) {
this.next = next;
}
judge(obj) {
if (condition) {
// do something
} else if (this.next) {
this.next.judge(obj);
} else {
// Error Handering
}
}
}
handler2 = new Handler2(null);
handler1 = new Handler1(handler2);
handler1.judge(obj)
命令模式
命令模式憋飞,命令模式需要一個(gè)invoker來執(zhí)行不同的命令,所有的命令需要在invoker注冊姆吭。然后Client通過invoker來調(diào)用命令榛做,然后在invoker里可以對所有的命令進(jìn)行一個(gè)記錄,就是history内狸。然后就可以進(jìn)行undo或者redo的操作检眯。每個(gè)命令基本上要有同樣的接口來指明命令的各種操作。操作名要一致昆淡。
class command1 () {
exec() {
}
}
class command2 () {
exec() {
}
}
class invoker () {
perform (name) {
switch (name)
case 'command1':
command1.exec()
break;
case 'command2':
command2.exec()
break;
default:
error
}
}
策略模式
策略模式是針對同一件事情的不同做法锰瘸,這點(diǎn)和命令模式的區(qū)別,命令模式是針對同一個(gè)對象的不同行為昂灵。所以這個(gè)模式往往是針對算法的封裝避凝。
class strategies() {
static strategy1 () {
}
static strategy2() {
}
}
modules.exports = strategies;
迭代器
迭代器模式的應(yīng)用場景就是需要經(jīng)常遍歷一個(gè)數(shù)據(jù)集合,但是我們數(shù)據(jù)集合的可能性很多眨补,或者會(huì)變管削。基本上迭代器就是要實(shí)現(xiàn)first撑螺, last含思, next, hasNext 這些基本的函數(shù)实蓬。
class iterator() {
first() {
}
last() {
}
next() {
}
hasNext() {
}
}
觀察者模式
就是定義了一個(gè)一對多的關(guān)系茸俭,一但這個(gè)一得狀態(tài)發(fā)生改變吊履,那么,其他的都要發(fā)生改變调鬓。
class A () {
constructor() {
this.event = new EventEmitter();
}
change() {
this.event.emit('change');
}
}
class B () {
constructor(event) {
this.event = event;
}
observe() {
this.event.on('change', () => {
});
}
}