我经常在Java中使用这样的构造:
public enum MyMartDiscountCard {
//List of enum instances
Progressive(3, 10, 0.01),
FixedPercent(5, 5, 0);
//Just like normal class with fields and methods
private int initial;
private int max;
private int ratio;
public MyMartDiscountCard(int initial, int max, float ratio){...}
public calculateDiscount(float totalSpent){
return Math.max(initial + totalSpent*ratio, max);
}
}现在我正在学习打字稿,并希望在其中使用类似的结构。
据我所知,TS规范不允许这样做。但是,有什么好的变通模式来声明方法和属性并将它们绑定到枚举实例吗?
发布于 2014-03-06 11:42:28
我是从你的问题推断出来的,所以这对你来说可能不是正确的答案;但我不明白你为什么需要一个enum。你有折扣卡的概念,有特别化。
与其写一个枚举,然后在整个程序切换和关闭类型卡时使用代码,不如使用多态性,这样您的整个程序只需要知道有什么东西是折扣卡,而根本不需要知道类型。
class DiscountCard {
constructor(private initial: number, private max: number, private ratio: number){
}
public calculateDiscount(totalSpent: number) {
return Math.max(this.initial + totalSpent * this.ratio, this.max);
}
}
class ProgressiveDiscountCard extends DiscountCard {
constructor() {
super(3, 10, 0.01);
}
}
class FixedPercentDiscountCard extends DiscountCard {
constructor() {
super(5, 5, 0);
}
}
class DoubleFixedDiscountCard extends DiscountCard {
constructor() {
super(5, 5, 0);
}
public calculateDiscount(totalSpent: number){
var normalPoints = super.calculateDiscount(totalSpent);
return normalPoints * 2;
}
}DiscountCard的使用者不需要知道他们使用哪一张卡,因为您在专门化的逻辑中放置了任何变化。实际上,DoubleFixedDiscountCard可以用双值设置超类,但我想给出一个例子,您可以重写子类中的行为。
https://stackoverflow.com/questions/22221951
复制相似问题