我尝试学习扎实的原则。我写了两种类型的代码风格。哪一个是:
1)单一职责 Principle_2.cs :如果你看主程序,所有实例都是从接口(interface)生成的
1)单一职责 Principle_3.cs :如果你看主程序,所有实例都是从普通类生成的
我的问题:哪一个是正确的用法?我更喜欢哪一个?
namespace Single_Responsibility_Principle_2
{
class Program
{
static void Main(string[] args)
{
IReportManager raporcu = new ReportManager();
IReport wordraporu = new WordRaporu();
raporcu.RaporHazırla(wordraporu, "data");
Console.ReadKey();
}
}
interface IReportManager
{
void RaporHazırla(IReport rapor, string bilgi);
}
class ReportManager : IReportManager
{
public void RaporHazırla(IReport rapor, string bilgi)
{
rapor.RaporYarat(bilgi);
}
}
interface IReport
{
void RaporYarat(string bilgi);
}
class WordRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("Word Raporu yaratıldı:{0}",bilgi);
}
}
class ExcellRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("Excell raporu yaratıldı:{0}",bilgi);
}
}
class PdfRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("pdf raporu yaratıldı:{0}",bilgi);
}
}
}
第二个0ne所有实例都是从普通类生成的
namespace Single_Responsibility_Principle_3
{
class Program
{
static void Main(string[] args)
{
WordRaporu word = new WordRaporu();
ReportManager manager = new ReportManager();
manager.RaporHazırla(word,"test");
}
}
interface IReportManager
{
void RaporHazırla(IReport rapor, string bilgi);
}
class ReportManager : IReportManager
{
public void RaporHazırla(IReport rapor, string bilgi)
{
rapor.RaporYarat(bilgi);
}
}
interface IReport
{
void RaporYarat(string bilgi);
}
class WordRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("Word Raporu yaratıldı:{0}",bilgi);
}
}
class ExcellRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("Excell raporu yaratıldı:{0}",bilgi);
}
}
class PdfRaporu : IReport
{
public void RaporYarat(string bilgi)
{
Console.WriteLine("pdf raporu yaratıldı:{0}",bilgi);
}
}
}
最佳答案
您的示例与 SRP 无关。它涉及另一个面向对象的原则,即“接口(interface)编程”。我建议进行第一次实现。
SRP 表示,该类应该只有一个改变的理由。在您的情况下,您有两个不同的对象:ReportManager 和 Report。因此,根据SRP,ReportManager应该只负责管理报告实例,而Report应该负责报告目的。 ReportManager 可以扩展以包含有关可作为配置提供的各种类型的报告实现的信息,并且有时还可以负责创建实例。
关于c# - 单一职责原则用法如何正确调用子方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2934365/