JS设计模式-其他4-命令模式 & 备忘录模式

2019-03-23  本文已影响0人  林海_Mense

命令模式

概念
图示
image.png
代码演示
// 接收者
class Receiver {
    exec() {
        console.log("执行");
    }
}

// 命令者
class Command {
    constructor(receiver){
        this.receiver = receiver;
    }
    // 触发
    cmd() {
        console.log("执行命令")
        this.receiver.exec();
    }
}
// 触发者
class Invoker {
    constructor(command){
        this.command = command;
    }
    // 触发
    invoke() {
        console.log("开始")
        this.command.cmd();
    }
}

// 测试
// 士兵
let solider = new Receiver();
// 小号手
let trumpeter = new Command(solider);
// 将军
let general = new Invoker(trumpeter);
general.invoke();
// 开始
// 执行命令
// 执行
JS中的应用
// execCommand 浏览器封装富文本操作,复制,加粗选中文字等
document.execCommand("bold")
document.execCommand("undo")
设计原则验证

备忘录模式

概念
代码演示
// 状态备忘
class Memento {
    constructor(content){
        this.content = content;
    }
    getContent() {
        return this.content;
    }
}
// 备忘列表
class CareTaker {
    constructor(){
        this.list = []
    }
    add(memento){
        this.list.push(memento)
    }
    get(index){
        return this.list[index]
    }
}
// 编辑器
class Editor {
    constructor (){
        this.content = null;
    }
    setContent(content){
        this.content = content;
    }
    getContent(){
        return this.content;
    }
    // 保存
    saveContentToMemento(){
        return new Memento(this.content);
    }
    // 恢复
    getContentFromMemento(memento){
        this.content = memento.getContent();
    }
}
// 测试代码
let editor = new Editor();
let careTaker = new CareTaker();
editor.setContent("111");
editor.setContent('222')
careTaker.add(editor.saveContentToMemento());  // 存储备忘录
editor.setContent("333");
careTaker.add(editor.saveContentToMemento());
editor.setContent("444");

console.log(editor.getContent());
editor.getContentFromMemento(careTaker.get(1));
console.log(editor.getContent());
editor.getContentFromMemento(careTaker.get(0));
console.log(editor.getContent());

运行结果


运行结果.png
设计原则验证
上一篇 下一篇

猜你喜欢

热点阅读