依賴倒置原則(Dependence Inversion Principle)是程式要依賴於抽象接口,不要依賴於具體實現。簡單的說就是要求對抽象進行編程,不要對實現進行編程,這樣就降低了客戶與實現模組間的耦合。
基本介紹
- 中文名:依賴倒置原則
- 外文名:Dependence Inversion Principle
- 表達式:要依賴於抽象,不要依賴於具體
- 適用領域範圍:編程開發
意圖
代碼實現
public class HondaCar{ public void Run(){ Console.WriteLine("本田開始啟動了"); } public void Turn(){ Console.WriteLine("本田開始轉彎了"); } public void Stop(){ Console.WriteLine("本田開始停車了"); }}public class FordCar{ publicvoidRun(){ Console.WriteLine("福特開始啟動了"); } publicvoidTurn(){ Console.WriteLine("福特開始轉彎了"); } publicvoidStop(){ Console.WriteLine("福特開始停車了"); }}public class AutoSystem{ public enum CarType{ Ford,Honda }; private HondaCar hcar=new HondaCar(); private FordCar fcar=new FordCar(); private CarType type; public AutoSystem(CarType type){ this.type=type; } private void RunCar(){ if(type==CarType.Ford){ fcar.Run(); } else { hcar.Run(); } } private void TurnCar(){ if(type==CarType.Ford){ fcar.Turn(); } else { hcar.Turn(); } } private void StopCar(){ if(type==CarType.Ford){ fcar.Stop(); } else { hcar.Stop(); } }}
public class AutoSystem{public enum CarType{Ford,Honda,Bmw};HondaCar hcar=new HondaCar();FordCarf car=new FordCar();BmwCar bcar=new BmwCar();private CarType type;public AutoSystem(CarTypetype){this.type=type;}private void RunCar(){if(type==CarType.Ford){fcar.Run();}else if(type==CarType.Honda){hcar.Run();}else if(type==CarType.Bmw){bcar.Run();}}private void TurnCar(){if(type==CarType.Ford){fcar.Turn();}else if(type==CarType.Honda){hcar.Turn();}else if(type==CarType.Bmw){bcar.Turn();}}private void StopCar(){if(type==CarType.Ford){fcar.Stop();}else if(type==CarType.Honda){hcar.Stop();}else if(type==CarType.Bmw){bcar.Stop();}}}
結構圖
public interface ICar{void Run();void Turn();void Stop();}public class BmwCar:ICar{public void Run(){Console.WriteLine("寶馬開始啟動了");}public void Turn(){Console.WriteLine("寶馬開始轉彎了");}public void Stop(){Console.WriteLine("寶馬開始停車了");}}public class FordCar:ICar{publicvoidRun(){Console.WriteLine("福特開始啟動了");}public void Turn(){Console.WriteLine("福特開始轉彎了");}public void Stop(){Console.WriteLine("福特開始停車了");}}public class HondaCar:ICar{publicvoidRun(){Console.WriteLine("本田開始啟動了");}public void Turn(){Console.WriteLine("本田開始轉彎了");}public void Stop(){Console.WriteLine("本田開始停車了");}}public class AutoSystem{private ICar icar;public AutoSystem(ICar icar){this.icar=icar;}private void RunCar(){icar.Run();}private void TurnCar(){icar.Turn();}private void StopCar(){icar.Stop();}}