开闭原理C#:私有集+构造函数Init就是一个例子吗



My Workmate认为以下代码是C#中开闭原理的一个示例:

public class MyClass
{
public int Id { get; private set; }
public int Count{ get; private set; }
public int Maximum{ get; private set; }
public MyClass(int id, int count, int maximum)
{
Id = id;
Count = count;
Maximum = maximum;
}
public PrintValueWithText()
{
Conlose.Writeline($"The value of the Id property is: {Id.ToString()}");
}
}

他给出的理由是:"一旦构造了类,Id属性的值就被关闭以进行修改"。

我认为这是一个错误的解释。

我的理解是,开闭原则与为了修改而关闭的财产的价值无关。

我认为开放-关闭原则只与设计类有关,这样就可以在不修改现有代码的情况下扩展类的行为

即,如果我要进入并编辑CCD_ 1方法以也在新行上打印CCD_。因为我正在修改现有的类。

为了满足这一原则,我必须将类设计为可扩展的,这样我就可以通过组合注入打印功能。

这将允许我稍后添加打印功能,在新行上打印Maximum的值。

我对原则的解释正确吗?

他的解释不正确吗?

你是对的。Open-Closed原则与运行时的可变性或属性值无关。

开放-关闭原则是关于构建代码,这样我们就可以在不修改现有工作代码的情况下添加新的行为

我已经重写了您的代码以遵循OCP。在这种情况下,MyClass打开以进行扩展,从而通过引入新的IClassPrinter(在本例中为FancyClassPrinter(来打印Maximum属性。

请记住,使一个类完全封闭是不可能的,总会有我们无法预见的修改,所以OCP是一个指南而不是目标。

对于您的代码来说,这是一个有点做作的例子,对于这样简单的程序来说可能有些过头了。还要注意的是,单一责任原则要求我们将打印责任转移到另一个类别,即使我们没有遵循OCP。

using System;
using System.Collections.Generic;
public interface IClassPrinter{
void PrintValue(MyClass myClass);
}
public class NormalClassPrinter: IClassPrinter{
public void PrintValue(MyClass myClass)
{
Console.WriteLine($"The value of the Id property is: {myClass.Id.ToString()}");
}
}
public class FancyClassPrinter: IClassPrinter{
public void PrintValue(MyClass myClass)
{
Console.WriteLine($"The value of the Id property is: {myClass.Id.ToString()}");
Console.WriteLine($"The value of the Maximum property is: {myClass.Maximum.ToString()}");
}
}
public class MyClass
{
public int Id { get; private set; }
public int Count{ get; private set; }
public int Maximum{ get; private set; }
public MyClass(int id, int count, int maximum)
{
Id = id;
Count = count;
Maximum = maximum;
}
public void PrintValueWithText(IClassPrinter classPrinter)
{
classPrinter.PrintValue(this);
}
}
class MainClass
{
static public void Main(string[] args)
{
MyClass myClass = new MyClass(0,0,0);
myClass.PrintValueWithText(new NormalClassPrinter());
myClass.PrintValueWithText(new FancyClassPrinter());
}
}

相关内容

最新更新