首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将类型记录枚举视为类及其实例列表

问将类型记录枚举视为类及其实例列表
EN

Stack Overflow用户
提问于 2014-03-06 10:39:42
回答 1查看 227关注 0票数 0

我经常在Java中使用这样的构造:

代码语言:javascript
复制
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规范不允许这样做。但是,有什么好的变通模式来声明方法和属性并将它们绑定到枚举实例吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-06 11:42:28

我是从你的问题推断出来的,所以这对你来说可能不是正确的答案;但我不明白你为什么需要一个enum。你有折扣卡的概念,有特别化。

与其写一个枚举,然后在整个程序切换和关闭类型卡时使用代码,不如使用多态性,这样您的整个程序只需要知道有什么东西是折扣卡,而根本不需要知道类型。

代码语言:javascript
复制
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可以用双值设置超类,但我想给出一个例子,您可以重写子类中的行为。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22221951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档