策略模式
策略模式简单的来说就是为了减少if else的使用,让代码看起来更简洁
class Store1 {typeObj;
constructor(type: string) {
this.typeObj = type;
}
// 所有的逻辑都冗余在一起了
pay(amount: number) {
if(this.typeObj == "Normal") {
return amount;
} else if(this.typeObj == "Menber") {
return amount * 0.9;
} else if(this.typeObj == "VIP") {
return amount * 0.8;
}
}
}
let store1 = new Store1("VIP");
console.log(store1.pay(200));
使用策略模式后, 每个类都在自己的模块中使用,
class Store {
kindObj;
constructor(kind: any) {
this.kindObj = kind;
}
pay(amount: number) {
return this.kindObj.pay(amount);
}
}
class Normal {
pay(amount: number) {
return "普通: ¥" + amount;
}
}
class Menber {
pay(amount: number) {
return "商场员工: ¥" +amount*0.9;
}
}
class VIP {
pay(amount: number) {
return "会员: ¥" + amount*0.8;
}
}
let store = new Store(new Normal());
console.log(store.pay(100));