首页 > 其他分享 >typescript: Chain of Responsibility Pattern

typescript: Chain of Responsibility Pattern

时间:2023-10-11 09:15:33浏览次数:37  
标签:typescript handle string Pattern request handler Responsibility Handler return

 

/**
 * Chain of Responsibility Pattern 责任链是一种行为设计模式, 允许你将请求沿着处理者链进行发送, 直至其中一个处理者对其进行处理。
 * file: Chaints.ts
 * The Handler interface declares a method for building the chain of handlers.
 * It also declares a method for executing a request.
 */
interface Handler {
    /**
     * 
     * @param handler 
     */
    setNext(handler: Handler): Handler;
    /**
     * 
     * @param request 
     */
    handle(request: string): string;
}

/**
 * The default chaining behavior can be implemented inside a base handler class.
 */
abstract class AbstractHandler implements Handler
{
    /**
     * 
     */
    private nextHandler: Handler;
    /**
     * 
     * @param handler 
     * @returns 
     */
    public setNext(handler: Handler): Handler {
        this.nextHandler = handler;
        // Returning a handler from here will let us link handlers in a
        // convenient way like this:
        // monkey.setNext(squirrel).setNext(dog);
        return handler;
    }
    /**
     * 
     * @param request 
     * @returns 
     */
    public handle(request: string): string {
        if (this.nextHandler) {
            return this.nextHandler.handle(request);
        }

        return null;
    }
}

/**
 * All Concrete Handlers either handle a request or pass it to the next handler
 * in the chain.
 */
class MonkeyHandler extends AbstractHandler {
    /**
     * 
     * @param request 
     * @returns 
     */
    public handle(request: string): string {
        if (request === 'Banana') {
            return `Monkey: I'll eat the ${request}.`;
        }
        return super.handle(request);

    }
}

/**
 * 
 */
class SquirrelHandler extends AbstractHandler {
    /**
     * 
     * @param request 
     * @returns 
     */
    public handle(request: string): string {
        if (request === 'Nut') {
            return `Squirrel: I'll eat the ${request}.`;
        }
        return super.handle(request);
    }
}
/**
 * 
 * 
 */
class DogHandler extends AbstractHandler {

    /**
     * 
     * @param request 
     * @returns 
     */
    public handle(request: string): string {
        if (request === 'MeatBall') {
            return `Dog: I'll eat the ${request}.`;
        }
        return super.handle(request);
    }
}

/**
 * The client code is usually suited to work with a single handler. In most
 * cases, it is not even aware that the handler is part of a chain.
 */
function clientCodeChain(handler: Handler) {

    const foods = ['Nut', 'Banana', 'Cup of coffee'];
    let str="";
    for (const food of foods) {
        console.log(`Client: Who wants a ${food}?`);

        const result = handler.handle(food);
        if (result) {
            console.log(`  ${result}`);
            str=str+","+result;
        } else {
            console.log(`  ${food} was left untouched.`);
            str=str+","+food;
        }
    }
    return str;
}


let pubch1="";
let pubch2="";
let pubch3="Geovin Du";
let pubch4="geovindu";
/**
 * The other part of the client code constructs the actual chain.
 */
const monkey = new MonkeyHandler();
const squirrel = new SquirrelHandler();
const dog = new DogHandler();

monkey.setNext(squirrel).setNext(dog);

/**
 * The client should be able to send a request to any handler, not just the
 * first one in the chain.
 */
console.log('Chain: Monkey > Squirrel > Dog\n');
pubch1=clientCodeChain(monkey);
console.log('');

console.log('Subchain: Squirrel > Dog\n');
pubch2=clientCodeChain(squirrel);

let messageChain: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageChain+",<br/>one="+pubch1+",<br/>two="+pubch2+",<br/>three="+pubch3+",<br/>four="+pubch4+",<br/>TypeScript Chain of Responsibility 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 Chain of Responsibility 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/Chaints.js"></script>
    </body>
</html>

  

 

输出:

 

标签:typescript,handle,string,Pattern,request,handler,Responsibility,Handler,return
From: https://www.cnblogs.com/geovindu/p/17756211.html

相关文章

  • 【愚公系列】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......
  • typescript: Facade Pattern
     /***Facadepattern外观是一种结构型设计模式,能为复杂系统、程序库或框架提供一个简单(但有限)的接口。*TheFacadeclassprovidesasimpleinterfacetothecomplexlogicofoneor*severalsubsystems.TheFacadedelegatestheclientrequeststothe*......