High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions
public class Benz {
//汽车会跑
public void run(){
System.out.println("奔驰汽车开始运行...");
}
}
司机通过调用奔驰车的run方法开动奔驰车.
司机类:
public class Driver {
//司机的主要职责就是驾驶汽车
public void drive(Benz benz){
benz.run();
}
}
有车,有司机,在Client场景类产生相应的对象.
场景类:
public class Client {
public static void main(String[] args) {
Driver zhangSan = new Driver();
Benz benz = new Benz(); //张三开奔驰车
zhangSan.drive(benz);
}
}
public interface ICar {
public void run();
}
//奔驰汽车类
public class Benz implements ICar{
public void run(){
System.out.println("奔驰汽车开始运行...");
}
}
//宝马汽车类
public class BMW implements ICar{
public void run(){
System.out.println("宝马汽车开始运行...");
}
}
业务场景类:
public class Client {
public static void main(String[] args) {
IDriver zhangSan = new Driver();
ICar benz = new Benz();
//张三开奔驰车
zhangSan.drive(benz);
ICar bmw = new BMW();
//张三开宝马车
zhangSan.drive(bmw);
}
}
public interface IDriver {
//老司机,会开车
public void drive(ICar car);
}
public class Driver implements IDriver{
//司机的主要职责就是驾驶汽车
public void drive(ICar car){
car.run();
}
}