首页 > 其他分享 >typescript: Template Method pattern

typescript: Template Method pattern

时间:2023-10-11 18:34:59浏览次数:32  
标签:typescript console string pattern void protected strinuput Method log

 

/**
 * Template Method pattern 模版方法是一种行为设计模式, 它在基类中定义了一个算法的框架, 允许子类在不修改结构的情况下重写算法的特定步骤。
 * file: Templatets.ts
 * The Abstract Class defines a template method that contains a skeleton of some
 * algorithm, composed of calls to (usually) abstract primitive operations.
 *
 * Concrete subclasses should implement these operations, but leave the template
 * method itself intact.
 */
abstract class AbstractClass {


    /**
     * The template method defines the skeleton of an algorithm.
     * 
     * @param strinuput 
     * @returns
     */
    public templateMethod(strinuput:string): string { //void
        let getstr="";
        this.baseOperation1();
        getstr=this.requiredOperations1(strinuput);
        this.baseOperation2();
        this.hook1();
        this.requiredOperation2(strinuput);
        this.baseOperation3();
        this.hook2();
        return getstr;
    }

    /**
     * These operations already have implementations.
     */
    protected baseOperation1(): void {
        console.log('AbstractClass says: I am doing the bulk of the work');
    }
    /**
     * 
     */
    protected baseOperation2(): void {
        console.log('AbstractClass says: But I let subclasses override some operations');
    }
    /**
     * 
     */
    protected baseOperation3(): void {
        console.log('AbstractClass says: But I am doing the bulk of the work anyway');
    }

    /**
     * These operations have to be implemented in subclasses.
     * @param strinuput 
     * @returns
     */
    protected abstract requiredOperations1(strinuput:string):string; //void

    /**
     * 
     * @param strinuput 
     */
    protected abstract requiredOperation2(strinuput:string): void;

    /**
     * These are "hooks." Subclasses may override them, but it's not mandatory
     * since the hooks already have default (but empty) implementation. Hooks
     * provide additional extension points in some crucial places of the
     * algorithm.
     */
    protected hook1(): void { }
    /**
     * 
     */
    protected hook2(): void { }
}

/**
 * Concrete classes have to implement all abstract operations of the base class.
 * They can also override some operations with a default implementation.
 */
class ConcreteClass1 extends AbstractClass {

    /**
     * 
     * @param strinuput 
     * @returns
     */
    protected requiredOperations1(strinuput:string):string { //void
        console.log('ConcreteClass1 says: Implemented Operation1,'+strinuput);
        return 'ConcreteClass1 says: Implemented Operation1,'+strinuput;

    }
    /**
     * 
     * @param strinuput 
     */
    protected requiredOperation2(strinuput:string): void {
        console.log('ConcreteClass1 says: Implemented Operation2,'+strinuput);
    }
}

/**
 * Usually, concrete classes override only a fraction of base class' operations.
 */
class ConcreteClass2 extends AbstractClass {

    /**
     * 
     * @param strinuput 
     * @returns
     */
    protected requiredOperations1(strinuput:string): string { //void
        console.log('ConcreteClass2 says: Implemented Operation1,'+strinuput);
        return 'ConcreteClass2 says: Implemented Operation1,'+strinuput;
    }
    /**
     * 
     * @param strinuput 
     */
    protected requiredOperation2(strinuput:string): void {
        console.log('ConcreteClass2 says: Implemented Operation2,'+strinuput);
    }
    /**
     * 
     */
    protected hook1(): void {
        console.log('ConcreteClass2 says: Overridden Hook1');
    }
}

let pubTemplate1="";
let pubTemplate2="";
let pubTemplate3="Geovin Du";
let pubTemplate4="geovindu";


/**
 * The client code calls the template method to execute the algorithm. Client
 * code does not have to know the concrete class of an object it works with, as
 * long as it works with objects through the interface of their base class.
 * 客户端显示
 * @param abstractClass 
 * @param strinput 
 */
function clientCodeTemplate(abstractClass: AbstractClass,strinput:string) {
    // ...
   return abstractClass.templateMethod(strinput);
    // ...
}




console.log('Same client code can work with different subclasses:');

pubTemplate1=clientCodeTemplate(new ConcreteClass1(),"geovindu");

console.log('');

console.log('Same client code can work with different subclasses:');
pubTemplate2=clientCodeTemplate(new ConcreteClass2(),"geovindu");

let messageTemplate: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageTemplate+",<br/>one="+pubTemplate1+",<br/>two="+pubTemplate2+",<br/>three="+pubTemplate3+",<br/>four="+pubTemplate4+",<br/>TypeScript Template Method 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 Template Method 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/Templatets.js"></script>
    </body>
</html>

  

 

输出:

 

 

标签:typescript,console,string,pattern,void,protected,strinuput,Method,log
From: https://www.cnblogs.com/geovindu/p/17757892.html

相关文章

  • typescript: State Pattern
     /***StatePattern状态是一种行为设计模式,让你能在一个对象的内部状态变化时改变其行为。*TheContextdefinestheinterfaceofinteresttoclients.Italsomaintainsa*referencetoaninstanceofaStatesubclass,whichrepresentsthecurrent*stat......
  • typescript: Iterator Pattern
     /***IteratorPattern迭代器是一种行为设计模式,让你能在不暴露复杂数据结构内部细节的情况下遍历其中所有的元素*file:Iteratorts.tsnpminstall-gbabel-cli*Intent:Letsyoutraverseelementsofacollectionwithoutexposingits*underlyingrepres......
  • typescript: Memento Pattern
     /***MementoPattern备忘录是一种行为设计模式,允许生成对象状态的快照并在以后将其还原。*TheOriginatorholdssomeimportantstatethatmaychangeovertime.Italso*definesamethodforsavingthestateinsideamementoandanothermethodfor*re......
  • A Lightweight Method for Modeling Confidence in Recommendations with Learned Bet
    ALightweightMethodforModelingConfidenceinRecommendationswithLearnedBetaDistributions论文阅读笔记摘要​ 大多数推荐系统并不提供对其决策信心的指示。因此,他们不区分确定的建议和不确定的建议。现有的RecSys置信方法要么是不准确的启发式,要么是在概念上复杂,因......
  • typescript: Chain of Responsibility Pattern
     /***ChainofResponsibilityPattern责任链是一种行为设计模式,允许你将请求沿着处理者链进行发送,直至其中一个处理者对其进行处理。*file:Chaints.ts*TheHandlerinterfacedeclaresamethodforbuildingthechainofhandlers.*Italsodeclaresameth......
  • 【愚公系列】2023年10月 二十三种设计模式(九)-装饰者模式(Decorator Pattern)
    ......
  • Time Series Forecasting Methods
    基于EEMD-Prophet-LSTM的滑坡位移预测LSTM与Prophet时间序列预测实验11ClassicalTimeSeriesForecastingMethodsinMATLAB-FileExchange-MATLABCentral(mathworks.com)......
  • [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之间的耦合关系;    支持广播方式的通信......