Strategy Pattern
The core of this design pattern is to encapsulate changes in algorithms so that they can be replaced by each other.
Say nothing more, demand first: Shop checkouts require a statistical total purchase price of goods, and discounts, rebates and other preferential activities appear on the basis of the original prices.
Policy Pattern Class Diagram
Several policy methods inherit from the same abstract class and are instantiated through the context interface.
CashSuper Policy Abstract Class
abstract class CashSuper { public constructor() { } public abstract acceptCash(money: number); //Abstract Approach to Preferential Policies }
CashNormal Normal Normal Policy Class
class CashNormal extends CashSuper { public constructor() { super(); } public acceptCash(money: number): number { return money; } }
CashRebate Discount Policy Class
class CashRebate extends CashSuper { private moneyRebate: number = 1; public constructor(moneyRebate: number) { super(); this.moneyRebate = moneyRebate; } public acceptCash(money: number): number { money = money * this.moneyRebate; return money; } }
CashReturn Return Policy Class
class CashReturn extends CashSuper { private moneyCondition: number = 0; private moneyReturn: number = 0; public constructor(moneyCondition: number, moneyReturn: number) { super(); this.moneyCondition = moneyCondition; this.moneyReturn = moneyReturn; } public acceptCash(money: number): number { if (money >= this.moneyCondition) money = money - this.moneyReturn * Math.floor(money / this.moneyCondition); return money; } }
CashContext policy context interface (where different policy classes are instantiated in conjunction with simple factory mode)
class CashContext { public cs: CashSuper = null public constructor(type: string) { switch(type) { case "Normal": let cn: CashNormal = new CashNormal(); this.cs = cn; break; case "Rebate": let cb: CashRebate = new CashRebate(0.8); this.cs = cb; break; case "Return": let ct: CashReturn = new CashReturn(300, 100); this.cs = ct; break; } } public GetResult(money: number): number { return this.cs.acceptCash(money); } }
Client Test
let total: number = 1000; //Purchase original price let cc_1: CashContext = new CashContext("Normal"); // Original price let cc_2: CashContext = new CashContext("Return"); // Return strategy let cc_3: CashContext = new CashContext("Rebate"); // Discount strategy total = cc_1.GetResult(total); // 1000 total = cc_2.GetResult(total); // 1000 -> 700 total = cc_3.GetResult(total); // 700 -> 560
Advantages and disadvantages
Advantage: