高层 不依赖 低层 实现不依赖细节,二者都依赖接口
举例来说,如果设计一个软件来通过观察当前炉内的问题来控制火炉
开关,可以把程序写成如下形式:
public class Thermometer{
private int getCurrentTemp;
public int getGetCurrentTemp() {
// TODO Auto-generated method stub
return getCurrentTemp;
}
public void setGetCurrentTemp(int getCurrentTemp) {
this.getCurrentTemp = getCurrentTemp;
}
}
public class Furnace {
private static final int MAX_TEMP = 500;
private static final int MIN_TEMP = 100;
public void engage() {
DebugLog.log("too cold, open heater");
}
public void disengage() {
DebugLog.log("too hot, close heater");
}
public void regulate(Thermometer meter)
{
if(meter.getGetCurrentTemp()<MIN_TEMP)
this.engage();
if(meter.getGetCurrentTemp()>MAX_TEMP)
this.disengage();
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Furnace furnace=new Furnace();
Thermometer meter=new Thermometer();
meter.setGetCurrentTemp(90);
furnace.regulate(meter);
meter.setGetCurrentTemp(510);
furnace.regulate(meter);
}
}
那如有有一天检测温度的Thermometer 变成xxx Thermometer ,将会导致
Furnace 不能正常工作,我们都有一颗仁慈的心,当然希望世界和平。
public class Furnace implements Heater {
@Override
public void engage() {
DebugLog.log("too cold, open heater");
}
@Override
public void disengage() {
DebugLog.log("too hot, close heater");
}
}
public class FurnaceController {
public void regulate(Heater heater, Reader reader) {
if (reader.getGetCurrentTemp() < Reader.TEMPERATURE.MIN_TEMP) {
heater.engage();
}
if (reader.getGetCurrentTemp() > Reader.TEMPERATURE.MAX_TEMP) {
heater.disengage();
}
}
}
public interface Heater {
public void engage();
public void disengage();
}