标签:
1、依赖倒置的本质就是通过抽象(接口或者抽象类)使各个类或模块实现彼此独立。
public interface ICar{ public void run(); } public interface IDriver{ public void drive(ICar car); } public class Driver implements IDriver{ @Override public void drive(ICar car) { car.run(); } } public class Benz implements ICar{ @Override public void run() { System.out.println(" benz running"); } } public class Bmw implements ICar{ @Override public void run() { System.out.println(" bmw running"); } } public void main(String[] args){ IDriver wanglei = new Driver(); ICar benz = new Benz(); wanglei.drive(benz); }
依赖的三种写法:
1、构造函数传递依赖对象
public interface IDriver{ public void drive(); } public class Driver implements IDriver{ private ICar mCar; public void Driver(ICar car){ this.mCar = car; } @Override public void drive() { mCar.run(); } }
2、set方法传递依赖对象
public interface IDriver{ public void drive(); public void setCar(ICar car); } public class Driver implements IDriver{ private ICar mCar; @Override public void drive() { mCar.run(); } @Override public void setCar(ICar car) { this.mCar = car; } }
3、接口声明依赖对象
标签:
原文地址:http://www.cnblogs.com/wangqian-easy/p/4836215.html