我正在尝试这个问题以准备测试。根据我的理解,这是我最好的答案,但我觉得我可能会遗漏一些重要的事情。我认为我已经过多地改变了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)你重构的导航仪和GPS课程:(你将有更多的空间 真实的考验。)
(b)注入器代码(就像一系列语句一样)
我的回答:
(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);
答案 0 :(得分:0)
可能会更好。
public class Navigator {
private final Route theRoute;
private final MapView theMap;
public Navigator(Route inRoute, MapView theMap) {
theRoute = inRoute;
this.theMap = theMap;
}
public void setup() {
theRoute.calculateRoute();
}
public void display() {
theMap.plot(theRoute);
}
}
b)您的注射器代码不完整或错误
答案 1 :(得分:0)
Navigator
依赖于GPS
,因此您需要向导航器添加属性
public class Navigator
{
private GPS gps;
private UserInterface ui;
public Navigator(UserInterface ui, GPS gps) {
this.ui = ui;
this.gps = gps;
}
public void display() {
String destination = ui.getDestEntry().getText();
Route theRoute = new Route(gps.getLocation(), destination);
theRoute.calculateRoute();
MapView theMap = new MapView();
theMap.plot(theRoute);
}
}
public class GPS {
public String getLocation() { ... }
}
答案 2 :(得分:0)
我的c#重构变体看起来像:
public class ClientCode
{
void DoNavigations(IDestinationEntry ui, IGPS gps)
{
String destination = ui.getDestEntry().getText();
IRoute theRoute = new Route(gps.getLocation(), destination);
INavigator nv = new Navigator(theRoute);
nv.display();
}
}
public class Navigator : INavigator
{
private IRoute _theRoute;
public Navigator(IRoute theRoute)
{
_theRoute = theRoute;
_theRoute.calculateRoute();
}
public void display()
{
MapView theMap = new MapView();
theMap.plot(_theRoute);
}
}
public interface IGPS
{
string getLocation();
}
public interface INavigator
{
void display();
}
public interface IDestinationEntry
{
DestinationEntry getDestEntry();
}
public interface IRoute
{
void calculateRoute();
}