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

typescript: State Pattern

时间:2023-10-11 18:22:40浏览次数:51  
标签:typescript Context Pattern state getstr State let context

 

/**
 * State Pattern 状态是一种行为设计模式, 让你能在一个对象的内部状态变化时改变其行为。
 * The Context defines the interface of interest to clients. It also maintains a
 * reference to an instance of a State subclass, which represents the current
 * state of the Context.
 */
class Context {
    /**
     * @type {State} A reference to the current state of the Context.
     */
    private state: State;
    /**
     * 
     * @param state 
     */
    constructor(state: State) {
        this.transitionTo(state);
    }

    /**
     * The Context allows changing the State object at runtime.
     * @returns
     */
    public transitionTo(state: State):string  { //void
        let getstr="";
        console.log(`Context: Transition to ${(<any>state).constructor.name}.`);
        getstr="Context: Transition to."+ (<any>state).constructor.name.toString()+""; //
        this.state = state;
        this.state.setContext(this);
        return getstr;
    }

    /**
     * The Context delegates part of its behavior to the current State object.
     * @returns
     */
    public request1(): string  { //void
        let getstr="";
        this.state.handle1();
        getstr=this.state.handle1();
        return getstr;
    }
    /**
     * 
     * @returns 
     */
    public request2(): string  { //void
        let getstr="";
        this.state.handle2();
        getstr=this.state.handle2();
        return getstr;

    }
}

/**
 * The base State class declares methods that all Concrete State should
 * implement and also provides a backreference to the Context object, associated
 * with the State. This backreference can be used by States to transition the
 * Context to another State.
 */
abstract class State {
    protected context: Context;
    /**
     * 
     * @param context 
     */
    public setContext(context: Context) {
        this.context = context;
    }

    /**
     * 
     * @returns
     */
    public abstract handle1(): string; //void
    /**
     * 
     *  @returns
     */
    public abstract handle2():string ; //void
}

/**
 * Concrete States implement various behaviors, associated with a state of the
 * Context.
 */
class ConcreteStateA extends State {


    /**
     * 
     *  @returns
     */
    public handle1(): string { //void

        let getstr="";
        console.log('ConcreteStateA handles request1.');
        console.log('ConcreteStateA wants to change the state of the context.');
        getstr="ConcreteStateA handles request1."
        getstr=getstr+","+this.context.transitionTo(new ConcreteStateA());       
        return getstr;
    }
    /**
     * 
     *  @returns
     */
    public handle2(): string { //void
        let getstr="";
        console.log('ConcreteStateA handles request2.');
        getstr="ConcreteStateA handles request2.";
        getstr=getstr+","+this.context.transitionTo(new ConcreteStateB());
        return getstr;
    }
}

/**
 * 
 */
class ConcreteStateB extends State {

    /**
     * 
     *  @returns
     */
    public handle1():string  { //void
        let getstr="";
        console.log('ConcreteStateB handles request1.');
        getstr="ConcreteStateB handles request1.";
        getstr=getstr+","+this.context.transitionTo(new ConcreteStateB());
        return getstr;
    }
    /**
     * 
     *  @returns
     */
    public handle2(): string { //void
        let getstr="";
        console.log('ConcreteStateB handles request2.');
        console.log('ConcreteStateB wants to change the state of the context.');
        getstr="ConcreteStateB handles request2.";
        //this.context.transitionTo(new ConcreteStateA());
        getstr=getstr+","+this.context.transitionTo(new ConcreteStateA());
        return getstr;
    }
}


let pubState1="";
let pubState2="";
let pubState3="Geovin Du";
let pubState4="geovindu";

/**
 * The client code.
 */
const context = new Context(new ConcreteStateA());
pubState1=context.request1();
pubState2=context.request2()+","+context.transitionTo(new ConcreteStateA());


const contextB = new Context(new ConcreteStateB());
pubState3=contextB.request1();
pubState4=contextB.request2()+","+contextB.transitionTo(new ConcreteStateB());

let messageState: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageState+",<br/>one="+pubState1+",<br/>two="+pubState2+",<br/>three="+pubState3+",<br/>four="+pubState4+",<br/>TypeScript State 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 State 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/Statets.js"></script>
    </body>
</html>

  

 

输出:

 

 

标签:typescript,Context,Pattern,state,getstr,State,let,context
From: https://www.cnblogs.com/geovindu/p/17757879.html

相关文章

  • typescript: Iterator Pattern
     /***IteratorPattern迭代器是一种行为设计模式,让你能在不暴露复杂数据结构内部细节的情况下遍历其中所有的元素*file:Iteratorts.tsnpminstall-gbabel-cli*Intent:Letsyoutraverseelementsofacollectionwithoutexposingits*underlyingrepres......
  • typescript: Memento Pattern
     /***MementoPattern备忘录是一种行为设计模式,允许生成对象状态的快照并在以后将其还原。*TheOriginatorholdssomeimportantstatethatmaychangeovertime.Italso*definesamethodforsavingthestateinsideamementoandanothermethodfor*re......
  • typescript: Chain of Responsibility Pattern
     /***ChainofResponsibilityPattern责任链是一种行为设计模式,允许你将请求沿着处理者链进行发送,直至其中一个处理者对其进行处理。*file:Chaints.ts*TheHandlerinterfacedeclaresamethodforbuildingthechainofhandlers.*Italsodeclaresameth......
  • 【愚公系列】2023年10月 二十三种设计模式(九)-装饰者模式(Decorator Pattern)
    ......
  • StateFlow初步探究
    flow是如何工作的stateflow是建立在flow的基础上的,要理解stateflow,首先需要对flow有一定的了解,其实flow的原理很简单,不过是建立在了协程的基础上,假设没有协程,实际上flow就是用一个回调(FlowCollector)来进行工作的,加上了协程之后,由于协程支持中断和恢复,让flow可以匹配发送端和接......
  • [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之间又有什么样的区别呢?在选择开发语言时,又该如何抉择呢?本文将会深入对比这两种语言,讨论两种语言之间的关联和差异,并概述两种语言各自的优势......