typescript: Strategy Pattern

发布时间 2023-10-13 18:16:38作者: ®Geovin Du Dream Park™

 

/**
 * 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>

  

 

输出: