48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
/*
|
|
实例:
|
|
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
|
*/
|
|
|
|
interface Strategy {
|
|
pay(amount: number): string;
|
|
}
|
|
|
|
class CashStrategy implements Strategy {
|
|
pay(amount: number): string {
|
|
return `使用现金支付了${amount.toFixed(2)}元`;
|
|
}
|
|
}
|
|
|
|
class AlipayStrategy implements Strategy {
|
|
pay(amount: number): string {
|
|
return `使用支付宝支付了${amount.toFixed(2)}元`;
|
|
}
|
|
}
|
|
|
|
class Context {
|
|
private strategy: Strategy| null = null;
|
|
|
|
setStrategy(strategy: Strategy) {
|
|
this.strategy = strategy;
|
|
}
|
|
|
|
pay(amount: number): string {
|
|
if (!this.strategy) {
|
|
throw new Error("支付策略未设置");
|
|
}
|
|
return this.strategy.pay(amount);
|
|
}
|
|
}
|
|
|
|
(function(){
|
|
console.log("=========== 策略模式 ===========")
|
|
const context = new Context();
|
|
|
|
context.setStrategy(new CashStrategy());
|
|
console.log(context.pay(100));
|
|
|
|
context.setStrategy(new AlipayStrategy());
|
|
console.log(context.pay(200));
|
|
|
|
console.log("\n========= 策略模式结束 =========")
|
|
})() |