我正在尝试这个问题以准备测试。根据我的理解,这是我最好的答案,但我觉得我可能遗漏了一些重要的东西。我认为我已经过多地改变了 Navigator 的职责,但我看不到更好的方法。
问题是:
public class Navigator
{
private Route theRoute;
public Navigator(UserInterface ui) {
String destination = ui.getDestEntry().getText();
theRoute = new Route(GPS.getLocation(), destination);
theRoute.calculateRoute();
}
public void display() {
MapView theMap = new MapView();
theMap.plot(theRoute);
}
}
public class GPS {
public static String getLocation() { ... }
}
“{ ... }” stands for an algorithm that we do not need to examine, for our purposes.
重构 Navigator 和 GPS 类以符合依赖注入模式。不要改变他们的基本职责。
(a) 您重构的 Navigator 和 GPS 类:(在实际测试中您将有更多空间。)
(b) 注入器代码(就像一个语句序列)
我的回答:
(一种)
public class Navigator {
private Route theRoute;
private MapView theMap;
public Navigator (Route inRoute) {
theRoute = inRoute;
theRoute.calculateRoute();
}
public void display(MapView inMap) {
theMap = inMap;
theMap.plot(theRoute);
}
}
public class GPS {
public GPS(); //constructor
public String getLocation(){...}
}
(二)
喷油器代码:
UserInterface ui = new UserInterface;
String destination = new String(ui.getDestEntry().getText());
GPS gps = new GPS;
Route theRoute = new Route (GPS.getLocation(), destination);
new Navigator(theRoute);