责任链模式 (Chain of Responsibility)
责任链模式的一个典型的NodeJS的例子就是Express中的Middleware模型。往往是一个请求或者数据对象需要经过几道工序或者需要从几个handler中选择一个handler来处理这个对象。每个工序会对这个对象就行判断或者在这道工序上终止操作,要么会传递到下一个handler。所以这个设计模式,要求每个handler需要致命下一个handler是什么。然后每个handler需要有个判断条件,来判断是否需要传递到下一个handler还是在这个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)
命令模式
命令模式,命令模式需要一个invoker来执行不同的命令,所有的命令需要在invoker注册。然后Client通过invoker来调用命令,然后在invoker里可以对所有的命令进行一个记录,就是history。然后就可以进行undo或者redo的操作。每个命令基本上要有同样的接口来指明命令的各种操作。操作名要一致。
class command1 () {
exec() {
}
}
class command2 () {
exec() {
}
}
class invoker () {
perform (name) {
switch (name)
case 'command1':
command1.exec()
break;
case 'command2':
command2.exec()
break;
default:
error
}
}
策略模式
策略模式是针对同一件事情的不同做法,这点和命令模式的区别,命令模式是针对同一个对象的不同行为。所以这个模式往往是针对算法的封装。
class strategies() {
static strategy1 () {
}
static strategy2() {
}
}
modules.exports = strategies;
迭代器
迭代器模式的应用场景就是需要经常遍历一个数据集合,但是我们数据集合的可能性很多,或者会变。基本上迭代器就是要实现first, last, next, hasNext 这些基本的函数。
class iterator() {
first() {
}
last() {
}
next() {
}
hasNext() {
}
}
观察者模式
就是定义了一个一对多的关系,一但这个一得状态发生改变,那么,其他的都要发生改变。
class A () {
constructor() {
this.event = new EventEmitter();
}
change() {
this.event.emit('change');
}
}
class B () {
constructor(event) {
this.event = event;
}
observe() {
this.event.on('change', () => {
});
}
}