卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19856本站已运行344

如何使用C#实现单一职责原则?

如何使用C#实现单一职责原则?

一个类应该只有一个改变的理由。

定义 - 在这种情况下,责任被认为是改变的一个原因。

该原则指出,如果我们有两个原因要更改某个类,则必须将功能拆分为两个类。每个类仅处理一项职责,如果将来我们需要进行一项更改,我们将在处理它的类中进行更改。当我们需要对具有更多职责的类进行更改时,该更改可能会影响与该类的其他职责相关的其他功能。

示例

代码之前单一职责原则

'
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!");
         }
      }
   }
}
卓越飞翔博客
上一篇: PHP消息队列开发技巧:实现分布式日志收集器
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏