【发布时间】:2011-11-13 18:25:59
【问题描述】:
我有上课券:
public abstract class Voucher
{
public int Id { get; set; }
public decimal Value { get; protected set; }
public const string SuccessMessage = "Applied";
}
和一个子类 GiftVoucher
public class GiftVoucher : Voucher
{
}
和另一个子类 DiscountVoucher
public class DiscountVoucher : Voucher
{
public decimal Threshold { get; private set; }
public string FailureMessage { get { return "Please spend £{0} to use this discount"; } }
}
您可以看到 DiscountVoucher 有几个特定的属性 Threshold 和 FailureMessage,它们分别表示您需要花费的金额才能获得折扣,以及如果用户没有花费该金额则显示的失败消息。
我的问题是这样的。我有一组 Voucher 对象,我不想在我的代码中做这样的事情
if (voucher is DiscountVoucher)
{
// cast voucher to a DiscountVoucher and then call the specific methods on it
}
因为这根本不是可维护的。同时我不想把那些特定的方法放在 Voucher 抽象类中,因为它们并不适用于所有类型的 Voucher。有谁知道如何设计这个功能?
【问题讨论】:
-
您必须对您的收藏执行哪些任务?
标签: c# oop design-patterns