将typescript枚举作为具有其实例列表的类进行处理

时间:2014-03-06 10:39:43

标签: typescript

我经常在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);
    }
}

现在我正在学习Typescript,并希望在其中使用类似的结构。

据我所知,TS规范不允许这样做。但有没有任何好的解决方法模式来声明方法和属性并将它们绑定到枚举实例?

1 个答案:

答案 0 :(得分:1)

我是从你的问题推断出来的,所以这对你来说可能不是正确的答案;但我不明白为什么你需要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实际上只能设置具有doubled值的超类,但我想展示一个覆盖子类中行为的示例。