依赖倒置原则笔记

2022-07-28,,,

看如下一个例子:

pulic class Geely{

public void studyJavaCourse(){
System.out.println("Geely在学习Java");
}

public void studyFECourse(){
System.out.println("Geely在学习FE");
}

}
public class Test{

    
    public static void main(String[] args) {
        Geely geely = new Geely();
        geely.studyJavaCourse();
        geely.studyFECourse();
    }

}

现在要Geely要学习Python,就要按如下步骤:
先在Geely类增加studyPython方法

pulic class Geely{

public void studyJavaCourse(){
System.out.println("Geely在学习Java");
}

public void studyFECourse(){
System.out.println("Geely在学习FE");
}

public void studyPython(){
System.out.println("Geely在学习Python");
}

}

在主类调用:

public class Test{

    
    public static void main(String[] args) {
        Geely geely = new Geely();
        geely.studyJavaCourse();
        geely.studyFECourse();
        geely.studyPython();
    }

}

但这样做,使得高层Test类高度依赖底层Geely类的实现,不符合依赖倒置原则
一般我们提倡面对接口编程,所以我们先建一个ICourse接口,

public interface ICourse {


    void studyCourse();

}

然后具体实现有三个类实现
1.Javacourse类

public class JavaCourse implements ICourse {

    @Override
    public void studyCourse() {
        System.out.println("Geely在学习Java课程");
    }
}

2.FECourse类

public class FECourse implements ICourse {
    @Override
    public void studyCourse() {
        System.out.println("Geely在学习FE课程");
    }

}

3.新增的PythonCourse类

public class PythonCourse implements ICourse {
    @Override
    public void studyCourse() {
        System.out.println("Geely在学习Python课程");
    }
}

Geely类,现在Geely想学什么课程,都不要动自己的内容(相对JavaCourse,FECoure等等来说是高级),不依赖具体的类(JavaCourse,PythonCourse等等),核心是面对接口编程。

public class Geely {

    public void setiCourse(ICourse iCourse) {
        this.iCourse = iCourse;
    }

    private ICourse iCourse;

    public void studyImoocCourse(){
        iCourse.studyCourse();
    }

    
}

Test类

public class Test{

    public static void main(String[] args) {
        Geely geely = new Geely();
        geely.setiCourse(new JavaCourse());
        geely.studyImoocCourse();

        geely.setiCourse(new FECourse());
        geely.studyImoocCourse();

       geely.setiCourse(new PythonCourse());
        geely.studyImoocCourse();

    }


}

结构图如下:

本文地址:https://blog.csdn.net/ymqzll/article/details/109646726

《依赖倒置原则笔记.doc》

下载本文的Word格式文档,以方便收藏与打印。