当前位置: 首页 > 编程笔记 >

什么是依赖关系反转原理,以及如何在C#中实现?

宋晋
2023-03-14
本文向大家介绍什么是依赖关系反转原理,以及如何在C#中实现?,包括了什么是依赖关系反转原理,以及如何在C#中实现?的使用技巧和注意事项,需要的朋友参考一下

高级模块不应依赖于低级模块。两者都应该依赖抽象,抽象不应该依赖细节。细节应取决于抽象。此原则主要涉及减少代码模块之间的依赖性。

示例

依赖反转之前的代码

using System;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public class Email{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendEmail(){
         //发电子邮件
      }
   }
   public class SMS{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendSMS(){
         //发送短信
      }
   }
   public class Notification{
      private Email _email;
      private SMS _sms;
      public Notification(){
         _email = new Email();
         _sms = new SMS();
      }
      public void Send(){
         _email.SendEmail();
         _sms.SendSMS();
      }
   }
}

依赖反转后的代码

using System.Collections.Generic;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public interface IMessage{
      void SendMessage();
   }
   public class Email: IMessage{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendMessage(){
         //发电子邮件
      }
   }
   public class SMS: IMessage{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendMessage(){
         //发送短信
      }
   }
   public class Notification{
      private ICollection<IMessage> _messages;
      public Notification(ICollection<IMessage> messages){
         this._messages = messages;
      }
      public void Send(){
         foreach (var message in _messages){
            message.SendMessage();
         }
      }
   }
}
 类似资料:
  • 我正在使用一个库,它提供了一个c可执行文件的python包装器。 我安装它(https://github.com/bulletphysics/bullet3)使用venv(https://docs.python.org/3/library/venv.html)-一切都很好。 我正在考虑尝试构建 https://github.com/bulletphysics/bullet3 从venv文件夹的根目

  • 有人能帮我理解一下“假性依赖”是什么意思吗? 我的教授刚刚在这张幻灯片中解释了为什么我们不能在命令1之前运行命令3,但为什么后来他称之为“假”?

  • 在学习gradle时,我似乎是Java的构建工具。但我不明白依赖到底是什么。Gradle中的依赖项部分到底是什么意思?它有什么用途?

  • Every package built in LFS relies on one or more other packages in order to build and install properly. Some packages even participate in circular dependencies, that is, the first package depends on t

  • 借助Spring实现具有依赖关系的对象之间的解耦。 对象A运行需要对象B,由主动创建变为IOC容器注入,这便是控制反转。 获得依赖对象的过程被反转了,获取依赖对象的过程由自身创建变为由IOC容器注入,这便是依赖注入。

  • 我正在使用Gradle的Spring Boot框架。我知道,为了包含一些Spring依赖项,我可以引用“starters”而不显式定义版本;该版本将由我选择的Spring Boot版本控制,它是Spring Boot Gradle插件的版本。示例(省略非相关的分级代码): 请注意,没有为我的应用程序依赖项定义显式版本。 我如何确保我为那些依赖项使用的版本与我的其他Spring Boot依赖项兼容?