目录: html
设计模式六大原则:单一职责原则linux
设计模式六大原则:依赖倒置原则设计模式
依赖倒置原则(Dependence Inversion Principle): 学习
一、高层模块不该该依赖底层模块,两者都应该依赖抽象。this
二、抽象不该该依赖细节,细节应该依赖抽象。spa
三、依赖倒置的中心思想是面向接口编程。
四、依赖倒置原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础搭建的架构要稳定的多。
五、使用接口或抽象类的目的是指定好规范,而不涉及任何具体的操做,把展示细节的任务交给他们的实现类来完成。
经典案例:
三二班有个小明,想要学习C#,因而买了本《深刻理解C#》进行学习。
1 internal class Program 2 { 3 private static void Main(string[] args) 4 { 5 XiaoMing xm = new XiaoMing(); 6 xm.Study(new CSharp()); 7 } 8 } 9 10 internal class CSharp 11 { 12 public void ShowMsg() 13 { 14 Console.WriteLine("《深刻理解C#》"); 15 } 16 } 17 18 internal class XiaoMing 19 { 20 public void Study(CSharp cSharp) 21 { 22 cSharp.ShowMsg(); 23 } 24 }
过了一段时间,小明以为光学习一门太没有意思了。据说Linux比较好玩,因而买了本《鸟哥的私房菜Linux》。
1 internal class Program 2 { 3 private static void Main(string[] args) 4 { 5 XiaoMing xm = new XiaoMing(); 6 xm.Study(new CSharp()); 7 xm.Study(new Linux()); 8 } 9 } 10 11 internal class CSharp 12 { 13 public void ShowMsg() 14 { 15 Console.WriteLine("《深刻理解C#》"); 16 } 17 } 18 19 internal class Linux 20 { 21 public void ShowMsg() 22 { 23 Console.WriteLine("《鸟哥的私房菜Linux》"); 24 } 25 } 26 27 internal class XiaoMing 28 { 29 public void Study(CSharp cSharp) 30 { 31 cSharp.ShowMsg(); 32 } 33 34 public void Study(Linux linux) 35 { 36 linux.ShowMsg(); 37 } 38 }
小明是一个聪明的娃,过了一段时间学得差很少了,因而又想学习《设计模式》...就这样小明在不断学习中成长,而咱们的代码却愈来愈臃肿,变得难以维护。因为XiaoMing是一个高级模块而且是一个细节实现类,此类依赖了书籍CSharp和Linux又是一个细节依赖类,这致使XiaoMing每读一本书都须要修改代码,这与咱们的依赖倒置原则是相悖的。那如何解决XiaoMing的这种问题呢?
1 internal class Program 2 { 3 private static void Main(string[] args) 4 { 5 XiaoMing xm = new XiaoMing(); 6 xm.Study(new CSharp()); 7 xm.Study(new Linux()); 8 } 9 } 10 11 internal interface IBook 12 { 13 void ShowMsg(); 14 } 15 16 internal class CSharp : IBook 17 { 18 public void ShowMsg() 19 { 20 Console.WriteLine("《深刻理解C#》"); 21 } 22 } 23 24 internal class Linux : IBook 25 { 26 public void ShowMsg() 27 { 28 Console.WriteLine("《鸟哥的私房菜Linux》"); 29 } 30 } 31 32 internal class XiaoMing 33 { 34 public void Study(IBook book) 35 { 36 book.ShowMsg(); 37 } 38 }
咱们发现,只要让XiaoMing依赖于抽象IBook,其余书籍依赖于该抽象,之后无论小明读什么书,哈哈都是so easy的。
依赖关系传递的三种方式:
一、经过接口传递(上述示例)
1 internal class XiaoMing 2 { 3 // 2.经过接口传递依赖对象 4 public void Study(IBook book) 5 { 6 book.ShowMsg(); 7 } 8 }
二、经过构造方法传递
1 internal class XiaoMing 2 { 3 private IBook _book; 4 5 // 1.经过构造函数传递依赖对象 6 public XiaoMing(IBook book) 7 { 8 this._book = book; 9 } 10 11 public void Study() 12 { 13 this._book.ShowMsg(); 14 } 15 }
三、经过Setter方法传递
1 internal class XiaoMing 2 { 3 private IBook _book; 4 5 // 3.经过Setter方法传递依赖对象 6 public void setBook(IBook _book) 7 { 8 this._book = _book; 9 } 10 11 public void Study() 12 { 13 this._book.ShowMsg(); 14 } 15 }
依赖倒置原则的本质就是经过抽象(接口或抽象类)使各个类或模块的实现彼此独立,不互相影响,实现模块间的松耦合。咱们在项目中使用这个原则要遵循下面的规则:
一、每一个类尽可能都有接口或者抽象类,或者抽象类和接口两都具有
二、变量的表面类型尽可能是接口或者抽象类
三、任何类都不该该从具体类派生
四、尽可能不要覆写基类的方法
五、若是基类是一个抽象类,而这个方法已经实现了,子类尽可能不要覆写。类间依赖的是抽象,覆写了抽象方法,对依赖的稳定性会有必定的影响
六、结合里氏替换原则使用