2014-03-06 39 views
0

我經常在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規範不允許它。但有沒有什麼好的解決方法模式來聲明方法和屬性並將它們綁定到枚舉實例?

回答

1

我從你的問題推斷,所以這可能不是你的正確答案;但我不明白你爲什麼需要這裏的enum。你有折扣卡的概念,專業化。

與其寫入一個枚舉,然後在整個程序切換過程中使用代碼,並且如果不使用卡的類型,請使用多態,以便您的整個程序只需要知道存在諸如折扣卡之類的東西,並且不會根本不需要知道類型。的DiscountCard

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; 
    } 
} 

消費者並不需要知道你把任何變化的邏輯專業化的內部,他們使用該卡。 DoubleFixedDiscountCard實際上可能只是設置了具有加倍值的超類,但是我想顯示一個例子,在其中覆蓋子類中的行爲。

+0

是的,我認爲這是個好主意。我固定在一個地方,像枚舉一樣。無論如何,我可以把所有這些派生類放入結構體枚舉中。 – setec