一个类应该只有一个改变的理由。
定义 – 在这种情况下,责任被认为是改变的一个原因。
该原则指出,如果我们有两个原因要更改某个类,则必须将功能拆分为两个类。每个类仅处理一项职责,如果将来我们需要进行一项更改,我们将在处理它的类中进行更改。当我们需要对具有更多职责的类进行更改时,该更改可能会影响与该类的其他职责相关的其他功能。
示例
代码之前单一职责原则
using System;using System.Net.Mail;namespace SolidPrinciples.Single.Responsibility.Principle.Before { class Program{ public static void SendInvite(string email,string firstName,string lastname){ if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){ throw new Exception("Name is not valid"); } if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"}) } }}
登录后复制
遵循单一职责原则编写代码
using System;using System.Net.Mail;namespace SolidPrinciples.Single.Responsibility.Principle.After{ internal class Program{ public static void SendInvite(string email, string firstName, string lastname){ UserNameService.Validate(firstName, lastname); EmailService.validate(email); SmtpClient client = new SmtpClient(); client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" }); } } public static class UserNameService{ public static void Validate(string firstname, string lastName){ if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){ throw new Exception("Name is not valid"); } } } public static class EmailService{ public static void validate(string email){ if (!email.Contains("@") || !email.Contains(".")){ throw new Exception("Email is not Valid!"); } } }}
登录后复制
以上就是如何使用C#实现单一职责原则?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2429567.html