我在准备测试时正在尝试这个问题。根据我的理解,这是我的最佳答案,但我觉得我可能错过了一些重要的东西。我认为我已经改变了导航器的责任,但我看不到更好的方式。依赖注入 - 我是否正确地重构了代码?
的问题是:
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.
重构导航和GPS类,以符合依赖注入模式。不要改变他们的基本职责。
(a)您重构导航和GPS类:(你会对 真正的考验更多的空间)
(二)喷油器的代码(就像语句序列)
我答案:
的(a)
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(){...}
}
(b)
喷油器代码:
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);
谢谢,我忘了打电话给注册导航员r代码,那你的意思是不完整的? – Sarah
嗯,是:) Navigator nav = new Navigator(theRoute); nav.display(地图); – MariuszS
注射器代码在这里只有两行:RouteRoute = new Route(GPS.getLocation(),destination); 新导航(theRoute); 其他代码与喷油器无关 – MariuszS