面向接口编程 --对象的三种依赖
模块间的依赖通过抽象来发生,实现类之间不应该有直接的依赖关系,依赖关系通过接口或抽象类来产生, 即面向接口编程。通过面向接口编程,当业务逻辑发生变化时,只需要修改业务场景的客户端调用类,不要修改低层的模块,降低维护成本,减少风险产生。
接口依赖注入:
驾驶员接口及实现类
public interface IDriver {
public void driver(ICar car);
}
public class Driver implements IDriver{
@Override
public void driver(ICar car) {
// TODO Auto-generated method stub
car.running();
}
}
汽车接口及实现类
public interface ICar {
public void running();
}
public class BMW implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("宝马行驶..");
}
}
public class Benz implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("奔驰行驶..");
}
}
场景客户端调用
public class Benz implements ICar{
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("奔驰行驶");
}
}
构造器依赖注入:
驾驶员接口及实现类
public interface IDriver {
public void drive();
}
public class Driver implements IDriver{
private ICar car;
public Driver(ICar _car) {
this.car = _car;
}
@Override
public void drive() {
// TODO Auto-generated method stub
car.running();
}
}
汽车接口及实现类
public interface ICar {
public void running();
}
public class BMW implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("宝马行驶..");
}
}
public class Benz implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("奔驰行驶..");
}
}
场景客户端调用
public class Client {
public static void main(String[] args) {
IDriver driver = new Driver(new Benz());
driver.drive();
}
}
Setter依赖注入:
驾驶员接口及实现类
public interface IDriver {
public void drive();
public void setCar(ICar car);
}
public class Driver implements IDriver {
private ICar car;
@Override
public void drive() {
// TODO Auto-generated method stub
car.running();
}
public ICar getCar() {
return car;
}
public void setCar(ICar _car) {
this.car = _car;
}
}
汽车接口及实现类
public interface ICar {
public void running();
}
public class BMW implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("宝马行驶..");
}
}
public class Benz implements ICar {
@Override
public void running() {
// TODO Auto-generated method stub
System.out.println("奔驰行驶..");
}
}
场景客户端调用
public class Client {
public static void main(String[] args) {
IDriver driver = new Driver();
driver.setCar(new Benz());
driver.drive();
}
}