首页 > 其他分享 >typescript: Memento Pattern

typescript: Memento Pattern

时间:2023-10-11 18:12:44浏览次数:104  
标签:Originator originator typescript string Pattern state Memento memento

 

/**
 * Memento Pattern 备忘录是一种行为设计模式, 允许生成对象状态的快照并在以后将其还原。
 * The Originator holds some important state that may change over time. It also
 * defines a method for saving the state inside a memento and another method for
 * restoring the state from it.
 */
class Originator {
    /**
     * For the sake of simplicity, the originator's state is stored inside a
     * single variable.
     */
    private state: string;
    /**
     * 
     * @param state 
     */
    constructor(state: string) {
        this.state = state;
        console.log(`Originator: My initial state is: ${state}`);
    
    }

    /**
     * The Originator's business logic may affect its internal state. Therefore,
     * the client should backup the state before launching methods of the
     * business logic via the save() method.
     */
    public doSomething(): void {
        console.log('Originator: I\'m doing something important.');
        this.state = this.generateRandomString(30);
        console.log(`Originator: and my state has changed to: ${this.state}`);
    }
    /**
     * 
     * @param length 
     * @returns 
     */
    private generateRandomString(length: number = 10): string {
        const charSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        return Array
            .apply(null, { length })
            .map(() => charSet.charAt(Math.floor(Math.random() * charSet.length)))
            .join('');
    }

    /**
     * Saves the current state inside a memento.
     */
    public save(): Memento {
        return new ConcreteMemento(this.state);
    }

    /**
     * Restores the Originator's state from a memento object.
     */
    public restore(memento: Memento): void {
        this.state = memento.getState();
        console.log(`Originator: My state has changed to: ${this.state}`);
    }
}

/**
 * The Memento interface provides a way to retrieve the memento's metadata, such
 * as creation date or name. However, it doesn't expose the Originator's state.
 */
interface Memento {

    /**
     * 
     *  @returns
     */
    getState(): string;

    /**
     * 
     *  @returns
     */
    getName(): string;

    /**
     * 
     *  @returns
     */
    getDate(): string;
}

/**
 * The Concrete Memento contains the infrastructure for storing the Originator's
 * state.
 */
class ConcreteMemento implements Memento {
    private state: string;

    private date: string;
    /**
     * 
     * @param state 
     */
    constructor(state: string) {
        this.state = state;
        this.date = new Date().toISOString().slice(0, 19).replace('T', ' ');
    }

    /**
     * The Originator uses this method when restoring its state.
     *  @returns
     */
    public getState(): string {
        return this.state;
    }

    /**
     * The rest of the methods are used by the Caretaker to display metadata.
     *  @returns
     */
    public getName(): string {
        return `${this.date} / (${this.state.substr(0, 9)}...)`;
    }

    /**
     * 
     * @returns 
     */
    public getDate(): string {
        return this.date;
    }
}

/**
 * The Caretaker doesn't depend on the Concrete Memento class. Therefore, it
 * doesn't have access to the originator's state, stored inside the memento. It
 * works with all mementos via the base Memento interface.
 */
class Caretaker {

    private mementos: Memento[] = [];

    private originator: Originator;
    /**
     * 
     * @param originator 
     */
    constructor(originator: Originator) {
        this.originator = originator;
    }
    /**
     * 
     */
    public backup(): void {
        console.log('\nCaretaker: Saving Originator\'s state...');
        this.mementos.push(this.originator.save());
    }
    /**
     * 
     * @returns 
     */
    public undo(): void {


        if (!this.mementos.length) {
            return;
        }
        const memento = this.mementos.pop();

        console.log(`Caretaker: Restoring state to: ${memento.getName()}`);
        this.originator.restore(memento);
    }
    /**
     * 
     *  @returns
     */
    public showHistory(): string { //void
        let getstr="";
        console.log('Caretaker: Here\'s the list of mementos:');
        for (const memento of this.mementos) {
            console.log(memento.getName());
            getstr=getstr+memento.getName()+","+memento.getState();
           // return memento.getName();
        }

        return getstr;
    }
}


let pubMemento1="";
let pubMemento2="";
let pubMemento3="Geovin Du";
let pubMemento4="geovindu";
/**
 * Client code.
 */
const originator = new Originator('Super-duper-super-puper-super.');
const caretaker = new Caretaker(originator);

caretaker.backup();
originator.doSomething();

caretaker.backup();
originator.doSomething();

caretaker.backup();
originator.doSomething();

console.log('');
pubMemento1=pubMemento1+caretaker.showHistory();

console.log('\nClient: Now, let\'s rollback!\n');
caretaker.undo();

console.log('\nClient: Once more!\n');
caretaker.undo();

let messageMemento: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageMemento+",<br/>one="+pubMemento1+",<br/>two="+pubMemento2+",<br/>three="+pubMemento3+",<br/>four="+pubMemento4+",<br/>TypeScript Memento Pattern 备忘录模式";

  

调用:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <head><title>TypeScript Hello Memento Pattern 备忘录</title>
      <meta name="Description" content="geovindu,涂聚文,Geovin Du"/>
<meta name="Keywords" content="geovindu,涂聚文,Geovin Du"/>
<meta name="author" content="geovindu,涂聚文,Geovin Du"/> 
    </head>
    <body>

        <script src="dist/Mementots.js">
 //
            //type="module"
        </script>

    </body>
</html>

  

 

输出:

 

标签:Originator,originator,typescript,string,Pattern,state,Memento,memento
From: https://www.cnblogs.com/geovindu/p/17757864.html

相关文章

  • typescript: Chain of Responsibility Pattern
     /***ChainofResponsibilityPattern责任链是一种行为设计模式,允许你将请求沿着处理者链进行发送,直至其中一个处理者对其进行处理。*file:Chaints.ts*TheHandlerinterfacedeclaresamethodforbuildingthechainofhandlers.*Italsodeclaresameth......
  • 【愚公系列】2023年10月 二十三种设计模式(九)-装饰者模式(Decorator Pattern)
    ......
  • [Typescript] Type and Interface for performance
    Let'ssayyou'recreatingacomponentthathasallthepropsof input butneedstoadda label prop.You'llneedtoextendfromthe ComponentProps typehelperimport{ComponentProps}from"react";exporttypeInputProps=Co......
  • typescript: Flyweight Pattern
     /***FlyweightPattern享元是一种结构型设计模式,它允许你在消耗少量内存的情况下支持大量对象。*https://refactoringguru.cn/design-patterns/flyweight/typescript/example#lang-features*TheFlyweightstoresacommonportionofthestate(alsocalledintr......
  • 设计模式之 Observer Pattern观察者模式
    观察者模式Observer  Observer模式为组件向相关接收方【广播】消息提供了灵活的方法;  该模式定义了对象一到多的依赖关系,这样当对象改变状态时,将自动通知并更新他所有的依赖对象;  优点    抽象了主体与Observer之间的耦合关系;    支持广播方式的通信......
  • 【愚公系列】2023年10月 二十三种设计模式(八)-组合模式(Composite Pattern)
    ......
  • TypeScript与JavaScript比较(区别)
     TypeScript和JavaScript是目前项目开发中较为流行的两种脚本语言,TypeScript是JavaScript的一个超集,但是TypeScript与JavaScript之间又有什么样的区别呢?在选择开发语言时,又该如何抉择呢?本文将会深入对比这两种语言,讨论两种语言之间的关联和差异,并概述两种语言各自的优势......
  • TypeScript基础
    基础类型:":"后面为变量的数据类型布尔值:booleanletisDone:boolean=false数字:numberTypeScript中的所有数字类型都是浮点数,类型统一都是number,支持十进制,二进制,八进制,十六进制。letcount:number=100字符串:stringTypescript中使用string表示文本数据类型,可以使用双引......
  • 【愚公系列】2023年10月 二十三种设计模式(七)-桥接模式(Bridge Pattern)
    ......
  • 设计模式之 State Pattern状态模式
    State模式允许对象在内部状态变化时,变更其行为,并修改其类;优点:定位指定状态的行为,并且针对不同状态来划分行为,使状态转换显式进行;适用:对象的行为依赖于其状态,并且该对象必须在运行时根据其状态修改其行为;操作具有大量的以及多部分组成的取决于对象状态的条件语句; publicc......