什么是依赖注入 IoC
作者:互联网
高耦合例子
这里是一个爸爸给孩子讲故事的例子,都是通过new来实例化类
class Program { static void Main(string[] args) { Father father = new Father(); father.Read(); } } public class Book { public string GetContent() { return "很久很久以前,有个人叫盘古"; } } public class Father { public void Read() { Book book = new Book(); Console.WriteLine("爸爸开始讲故事了"); Console.WriteLine(book.GetContent()); } }
突然有一天,孩子不想听故事了,想听报纸上的内容。这里有需要添加一个报纸类
class Program { static void Main(string[] args) { Father father = new Father(); father.Read(); } } public class Book { public string GetContent() { return "很久很久以前,有个人叫盘古"; } } public class paper { public string GetContent() { return "报纸内容。。。。"; } } public class Father { public void Read() { //Book book = new Book(); //Console.WriteLine("爸爸开始讲故事了"); //Console.WriteLine(book.GetContent()); paper paper = new paper(); Console.WriteLine("爸爸开始读报纸了"); Console.WriteLine(paper.GetContent()); } }
这里发现 Father 被修改了,突然有一天小孩又想听看网页上的新闻。。。这里Father内容是不是又要修改了呢? 那肯定是的,这样Father会不断的被修改,耦合度太高,导致代码被频繁修改。这里能不能解耦呢?哎,那就用接口吧,降低耦合。来定义个接口
public interface IReader { string GetContent(); }
让 Book和paper 继承 IReader
class Program { static void Main(string[] args) { //先来读书 Father father = new Father(new Book()); father.Read(); } } public interface IReader { string GetContent(); } public class Book:IReader { public string GetContent() { return "很久很久以前,有个人叫盘古"; } } public class Paper : IReader { public string GetContent() { return "报纸内容。。。。"; } } public class Father { public IReader Reader { get; set; } //通过构造函数实例化接口 public Father(IReader reader) { Reader = reader; } public void Read() { //Book book = new Book(); //Console.WriteLine("爸爸开始讲故事了"); //Console.WriteLine(book.GetContent()); //paper paper = new paper(); //Console.WriteLine("爸爸开始读报纸了"); //Console.WriteLine(paper.GetContent()); Console.WriteLine("爸爸开始了。。"); Console.WriteLine(Reader.GetContent()); } }
在换一下Paper
static void Main(string[] args) { //先来读书 Father father = new Father(new Paper()); father.Read(); }
这样就实现了解耦。不用频繁修复Father,而是在调用的时候,随便调用。
标签:依赖,Console,Father,WriteLine,new,GetContent,IoC,public,注入 来源: https://www.cnblogs.com/youmingkuang/p/11963404.html