设计模式之依赖倒置原则

依赖倒置原则(Dependence Inversion Principle,简称DIP)面向接口编程,多态(接口类或者抽象类)

高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖实现类;实现类应该依赖抽象。 一旦依赖的低层或者具体类改动,则高层可能会需要改动

 

错误做法: //高层Driver模块不应该依赖低层DaZhong模块

public class DaZhong {
    public void startup(){
        System.out.println("车子启动了");
    }
}

//高层Driver模块不应该依赖低层DaZhong模块
public class Driver { public void driver(DaZhong vehicle){ vehicle.startup(); } } public class TaskTest { public static void main(String[] args) { Driver driver2 = new Driver(); DaZhong dz2 = new DaZhong(); driver2.driver(dz2); } }

 

 

正确做法:抽象IDriver依赖抽象IVehicle;具体的DaZhongVehicle依赖于抽象IVehicle,依赖倒置了

public interface IDriver {
    //接口声明依赖对象,接口注入IVehicle,抽象IDriver依赖抽象IVehicle
    void driver(IVehicle vehicle);
}

public class BaoMaDriver implements IDriver {
    IVehicle vehicle;

    //构造函数注入,DaZhongVehicle依赖IVehicle
    public  BaoMaDriver(IVehicle vehicle) {
        this.vehicle = vehicle;
    }
        public BaoMaDriver(){}

    public void driver(IVehicle vehicle) {
        vehicle.startup();
    }

    //set方法注入,DaZhongVehicle依赖IVehicle
    public void setVehicle(IVehicle vehicle) {
        this.vehicle = vehicle;
    }

}


public interface IVehicle {
    void startup();
}


public class DaZhongVehicle implements IVehicle {
    public void startup() {
        System.out.println("大众启动了");
    }

}

public class TaskTest {
    public static void main(String[] args) {
        IDriver driver = new BaoMaDriver();
        IVehicle dz = new DaZhongVehicle();
//这里变成了DaZhongVehicle依赖IVehicle,具体依赖于抽象,依赖倒置了

driver.driver(dz);
}
}

 

posted on 2019-01-30 18:01  lovebeauty  阅读(440)  评论(0编辑  收藏  举报

导航