【发布时间】:2020-07-03 02:18:19
【问题描述】:
我有一个任务,我需要实现一个基本的购物车系统。在此购物车中,将有适用于产品类别的不同类型的活动。这些活动将应用不同类型的折扣。为此,我决定实现工厂模式。
让我们从所有折扣类型的基类开始;
public abstract class Discount
{
public Category Category { get; set; }
public int MinimumItems { get; set; }
public Discount(Category category, int minItems)
{
Category = category;
MinimumItems = minItems;
}
}
活动界面;
public interface ICampaign
{
void ApplyDiscount(ShoppingCart card);
}
根据金额应用的广告系列类型(例如,价格折扣 100 美元);
public class AmountDiscount : Discount, ICampaign
{
public decimal DiscountAmount { get; set; }
public AmountDiscountGenerator(Category category, int minItems, decimal discountAmount) : base(category, minItems)
{
DiscountAmount = discountAmount;
}
public void ApplyDiscount(ShoppingCart card)
{
card.TotalPrice() -= DiscountAmount;
}
根据费率应用的广告系列类型(例如,价格折扣 %20);
public class RateDiscountGenerator : Discount, ICampaignGenerator
{
public double DiscountRate { get; set; }
public RateDiscountGenerator(Category category, int minItems, double discountRate) : base(category, minItems)
{
DiscountRate = discountRate;
}
public void ApplyDiscount(ShoppingCart card)
{
card.TotalPrice() -= card.TotalPrice() * DiscountRate / 100;
}
如您所见,ApplyDiscount() 方法的算法 上的不同活动类别不同。但是,不同之处在于其中一个具有名为DiscountAmount 的数据成员,另一个具有DiscountRate。
这是我实现的工厂类;
public static class CampaignFactory
{
public static ICampaign GenerateCampaign(Category category, int minItems, int amountOrRate, DiscountType discountType)
{
if(discountType == DiscountType.Amount)
{
return new AmountDiscountGenerator(category, minItems, amountOrRate);
}
else if(discountType == DiscountType.Rate)
{
return new RateDiscountGenerator(category, minItems, amountOrRate);
}
}
}
我的工厂类的问题是名为amountOrRate 的参数。要初始化属性DiscountAmount 或DiscountRate,我需要在我的工厂类中有一个公共参数,但是由于这个属性在语义上是不同的,所以在我的工厂方法和活动类中接受一个公共参数对我来说是错误的构造函数来分享一下(你可以从参数amountOrRate的命名理解我的困惑)。
您能帮我实现这个特定示例的模式吗?如果我需要使用工厂模式(例如策略模式)实现不同的设计模式,您也可以建议我。任何帮助表示赞赏,谢谢。
【问题讨论】:
-
与您的具体问题无关,但 'card.TotalPrice() -= DiscountAmount;'并且类似的代码将不起作用。 TotalPrice 返回一个值,修改后的值没有什么可写回的。
标签: c# oop design-patterns polymorphism factory-pattern