【发布时间】:2021-11-06 19:22:26
【问题描述】:
我正在尝试重构以下代码以遵守打开关闭原则
它为问题目的提取了一些代码,但基本上这里的计算方法根据发票类型表现不同
public class Invoice
{
private string _type;
public double Calculate(double amount)
{
if(_type == "invoice")
{
return amount + 10;
}
else
{
return amount - 10;
}
}
}
到这里为止
public interface IInvoice
{
double Calculate(double amount);
}
public class Invoice : IInvoice
{
public double Calculate(double amount)
{
return amount + 10;
}
}
public class DiscountInvoice : IInvoice
{
public double Calculate(double amount)
{
return amount - 10;
}
}
我从 API 端点获得以下模型,其中“类型”确定天气以使用 Invoice 或 DiscountInvoice。我喜欢避免将 if 条件放在类型字段上
public class InvoiceModel
{
public int Id { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
}
static void Main(string[] args)
{
private IInvoice _invoice;
//I am not sure how to detect and use the correct invoice type here. without doing below
//based on something i have to assign
_invoice = new Invoice() or new DiscountInvoice()
}
【问题讨论】:
-
您如何知道要创建哪种类型的发票?
-
@Chetan:我已经更新了这个问题,更详细一点,我想它会回答你的问题
标签: c# .net solid-principles open-closed-principle