有人能给我一个单一责任原则的例子吗?我试图理解,在实践中,一个班级有一个单一的责任,因为我担心我可能每天都违反这条规则.
oop single-responsibility-principle definition design-principles solid-principles
在下面的视频中,作者采用现有的类并为其分配单一责任原则.他选择了一个打印类,它具有访问数据,格式化和打印报告的功能.他将每个方法分解为自己的类,因此他创建了一个DataAccess类来处理数据访问,他创建了一个ReportFormatter类来处理Report的格式,并创建了一个ReportPrinter类来处理Report的打印.然后,原始的Report类保留一个方法Print(),该方法调用ReportPrinter的类方法Print.DataAccess和ReportFormatter似乎有责任,但ReportPrinter依赖于DataAcess和ReportFormatter,所以这不会破坏SRP或者我是否误解了它?
(感谢大家的答案,这是我的重构示例,反过来另一个关于单一责任原则的StackOverflow问题.)
从PHP到C#,这种语法令人生畏:
container.RegisterType<Customer>("customer1");
Run Code Online (Sandbox Code Playgroud)
直到我意识到它表达了同样的事情:
container.RegisterType(typeof(Customer), "customer1");
Run Code Online (Sandbox Code Playgroud)
正如我在下面的代码中演示的那样.
那么为什么在这里使用泛型(例如整个Unity和大多数C#IoC容器)有一些原因,除了它只是一个更清晰的语法,即你在发送类型时不需要typeof()?
using System;
namespace TestGenericParameter
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
container.RegisterType<Customer>("test");
container.RegisterType(typeof(Customer), "test");
Console.ReadLine();
}
}
public class Container
{
public void RegisterType<T>(string dummy)
{
Console.WriteLine("Type={0}, dummy={1}, name of class={2}", typeof(T), dummy, typeof(T).Name);
}
public void RegisterType(Type T, string dummy)
{
Console.WriteLine("Type={0}, dummy={1}, name of class={2}", T, dummy, T.Name);
}
}
public class Customer {}
}
//OUTPUT:
//Type=TestGenericParameter.Customer, …Run Code Online (Sandbox Code Playgroud)