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

typescript: Strategy Pattern

时间:2023-10-13 18:23:31浏览次数:39  
标签:typescript string GeovinStrategy Pattern strategy Context Strategy data

 

/**
 * Strategy Pattern 策略是一种行为设计模式, 它将一组行为转换为对象, 并使其在原始上下文对象内部能够相互替换。
 * 
 * file: Strategyts.ts
 * The Context defines the interface of interest to clients.
 */
class GeovinContext {
    /**
     * @type {GeovinStrategy} The Context maintains a reference to one of the Strategy
     * objects. The Context does not know the concrete class of a strategy. It
     * should work with all strategies via the Strategy interface.
     */
    private strategy: GeovinStrategy;

    /**
     * Usually, the Context accepts a strategy through the constructor, but also
     * provides a setter to change it at runtime.
     */
    constructor(strategy: GeovinStrategy) {
        this.strategy = strategy;
    }

    /**
     * Usually, the Context allows replacing a Strategy object at runtime.
     */
    public setStrategy(strategy: GeovinStrategy) {
        this.strategy = strategy;
    }

    /**
     * The Context delegates some work to the Strategy object instead of
     * implementing multiple versions of the algorithm on its own.
     */
    public doDuSomeBusinessLogic(): string  { //void
        // ...

        console.log('Context: Sorting data using the strategy (not sure how it\'ll do it)');
        const result = this.strategy.doAlgorithm(['a', 'b', 'c', 'd', 'e']);
        console.log(result.join(','));
        return result.join(",");
        // ...
    }
}

/**
 * The Strategy interface declares operations common to all supported versions
 * of some algorithm.
 *
 * The Context uses this interface to call the algorithm defined by Concrete
 * Strategies.
 */
interface GeovinStrategy {

    /**
     * 
     * @param data 
     */
    doAlgorithm(data: string[]): string[];
}

/**
 * Concrete Strategies implement the algorithm while following the base Strategy
 * interface. The interface makes them interchangeable in the Context.
 */
class ConcreteStrategyA implements GeovinStrategy {

    /**
     * 
     * @param data 
     * @returns 
     */
    public doAlgorithm(data: string[]): string[] {
        return data.sort();
    }
}

/**
 * 
 */
class ConcreteStrategyB implements GeovinStrategy {
    /**
     * 
     * @param data 
     * @returns 
     */
    public doAlgorithm(data: string[]): string[] {
        return data.reverse();
    }
}


let pubStrategy1="";
let pubStrategy2="";
let pubStrategy3="Geovin Du";
let pubStrategy4="geovindu";
/**
 * The client code picks a concrete strategy and passes it to the context. The
 * client should be aware of the differences between strategies in order to make
 * the right choice.
 */
const contextGeovin = new GeovinContext(new ConcreteStrategyA());
console.log('Client: Strategy is set to normal sorting.');
pubStrategy1=contextGeovin.doDuSomeBusinessLogic();

console.log('');

console.log('Client: Strategy is set to reverse sorting.');
contextGeovin.setStrategy(new ConcreteStrategyB());
pubStrategy2=contextGeovin.doDuSomeBusinessLogic();

let messageStrategy: string = 'Hello World,This is a typescript!,涂聚文 Geovin Du.Web';
document.body.innerHTML = messageStrategy+",<br/>one=Client: Strategy is set to normal sorting."+pubStrategy1+",<br/>two=Client: Strategy is set to reverse sorting."+pubStrategy2+",<br/>three="+pubStrategy3+",<br/>four="+pubStrategy4+",<br/>TypeScript Strategy 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 Strategy 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/Strategyts.js"></script>
    </body>
</html>

  

 

输出:

 

 

标签:typescript,string,GeovinStrategy,Pattern,strategy,Context,Strategy,data
From: https://www.cnblogs.com/geovindu/p/17762870.html

相关文章

  • TypeScript数据类型
    TypeScript数据类型:string:字符串number:数字boolean:true/falsestring[]:数组any:可以是任何类型。当你不希望某个特定的值导致类型检查错误时,你可以使用它。以下都不会报编译异常letvalue:any;value.foo.bar;//OKvalue.trim();//OKvalue();//OKnewvalue();//OKvalue[0][......
  • [论文精读][基于点云的蛋白-配体亲和力]A Point Cloud-Based Deep Learning Strategy
    我需要的信息代码,论文不考虑共价键,每个点包括了六种原子信息,包括xyz坐标,范德华半径,原子重量以及来源(1是蛋白质,-1是配体)。原子坐标被标准化,其它参数也被标准化。对不足1024个原子的的复合体,补0到1024。增加考虑的原子从1024到2048,没有提升,增加原子信息通道,没有提升(见resul......
  • 【愚公系列】2023年10月 二十三种设计模式(十一)-享元模式(Flyweight Pattern)
    ......
  • typescript: Observer Pattern
     /***ObserverPattern观察者是一种行为设计模式,允许一个对象将其状态的改变通知其他对象*file:Observerts.ts*TheSubjectinterfacedeclaresasetofmethodsformanagingsubscribers.*/interfaceGeovinSubject{//Attachanobservertothesub......
  • 机器学习经典教材《模式识别与机器学习》,Pattern Recognition and Machine Learning,PR
     微软剑桥研究院实验室主任ChristopherBishop的经典著作《模式识别与机器学习》,PatternRecognitionandMachineLearning,简称PRML,被微软“开源”了。  =================================  本书介绍&下载页:(书的介绍页面)https://www.microsoft.com/en-us/research......
  • typescript: Mediator pattern
     /****Mediatorpattern中介者是一种行为设计模式,让程序组件通过特殊的中介者对象进行间接沟通,达到减少组件之间依赖关系的目的。*file:Mediatorts.ts*TheMediatorinterfacedeclaresamethodusedbycomponentstonotifythe*mediatoraboutvarious......
  • typesciprt: Command Pattern
     /****CommandPattern命令是一种行为设计模式,它可将请求或简单操作转换为一个对象。*file:Commandts.ts*TheCommandinterfacedeclaresamethodforexecutingacommand.**/interfaceCommand{execute():string;//void}/***Somecomm......
  • 【愚公系列】2023年10月 二十三种设计模式(十)-外观模式(Facade Pattern)
    ......
  • typescript: Template Method pattern
     /***TemplateMethodpattern模版方法是一种行为设计模式,它在基类中定义了一个算法的框架,允许子类在不修改结构的情况下重写算法的特定步骤。*file:Templatets.ts*TheAbstractClassdefinesatemplatemethodthatcontainsaskeletonofsome*algorithm,......
  • typescript: State Pattern
     /***StatePattern状态是一种行为设计模式,让你能在一个对象的内部状态变化时改变其行为。*TheContextdefinestheinterfaceofinteresttoclients.Italsomaintainsa*referencetoaninstanceofaStatesubclass,whichrepresentsthecurrent*stat......