1. 程式人生 > >依賴倒置原則

依賴倒置原則

com 抽象 .com ava pack sta des this 模塊

1.定義:高層模塊不應該依賴低層模塊,二者都應該依賴其抽象

2.抽象不應該依賴細節,細節應該依賴抽象

3.針對接口編程,不要針對實現編程

4.優點:可以減少類間的耦合性、提高系統穩定性,提高代碼可讀性和可維護性,可降低修改程序所造成的風險

5.實例目錄package

技術分享圖片

6.UML類圖

技術分享圖片

7.代碼

1 package com.geely.design.principle.dependenceinversion;
2 
3 public interface ICourse {
4     void studyCourse();
5 }
1 package com.geely.design.principle.dependenceinversion;
2 3 public class JavaCourse implements ICourse{ 4 public void studyCourse() { 5 System.out.println("Geely在學習Java課程"); 6 } 7 }
1 package com.geely.design.principle.dependenceinversion;
2 
3 public class PythonCourse implements ICourse {
4     public void studyCourse() {
5         System.out.println("Geely在學習Python課程");
6 } 7 }
1 package com.geely.design.principle.dependenceinversion;
2 
3 public class FECourse implements ICourse {
4     public void studyCourse() {
5         System.out.println("Geely在學習FE課程");
6     }
7 }
 1 package com.geely.design.principle.dependenceinversion;
 2 
 3 public class Geely {
4 private ICourse iCourse; 5 6 public Geely(){ 7 8 } 9 public Geely(ICourse iCourse){ 10 this.iCourse = iCourse; 11 } 12 public void studyImoocCourse(){//ICourse iCourse 13 iCourse.studyCourse(); 14 } 15 16 public void setiCourse(ICourse iCourse){ 17 this.iCourse = iCourse; 18 } 19 /*public void studyJavaCourse(){ 20 System.out.println("Geely在學習Java課程"); 21 } 22 public void studyFECourse(){ 23 System.out.println("Geely在學習FE課程"); 24 } 25 public void studyPythonCourse(){ 26 System.out.println("Geely在學習Python課程"); 27 }*/ 28 }
 1 package com.geely.design.principle.dependenceinversion;
 2 
 3 public class Test {
 4     public static void main(String[] args){
 5         /*Geely geely = new Geely();
 6         geely.studyJavaCourse();
 7         geely.studyFECourse();
 8         geely.studyPythonCourse();*/
 9 
10         /*Geely geely = new Geely();
11         geely.studyImoocCourse(new JavaCourse());
12         geely.studyImoocCourse(new FECourse());
13         geely.studyImoocCourse(new PythonCourse());*/
14 
15         /*Geely geely = new Geely(new JavaCourse());
16         geely.studyImoocCourse();
17         Geely geely2 = new Geely(new FECourse());
18         geely2.studyImoocCourse();*/
19 
20         Geely geely = new Geely();
21         geely.setiCourse(new JavaCourse());
22         geely.studyImoocCourse();
23         geely.setiCourse(new FECourse());
24         geely.studyImoocCourse();
25     }
26 }

依賴倒置原則