【问题标题】:Open closed principle implementation开闭原则实现
【发布时间】: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


【解决方案1】:

首先你的结构看起来不错,符合开闭原则。

在确定使用哪个抽象实现方面,您需要考虑业务逻辑,因为决策直接取决于此。如果您有多个 IInvoice 实现,那么我假设您在应用程序中的某个时间点需要所有这些实现。因此,根据您的业务逻辑,您必须决定使用哪一个。 您可以考虑工厂模式,它会处理好并返回正确的类型。所有的业务逻辑都将封装在那里。只是在实现你的工厂时,还要记住 LSP (Liskov Substitution Principle),因为它很容易被破坏。

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多