将Java引用传递到对象链的最佳方法

Iva*_*hov 5 java parameter-passing

让我们考虑这样的对象链:

Earth->Continent->Country->City->name
Run Code Online (Sandbox Code Playgroud)

我们还考虑Earth.classpublic static void main(String[] args)

当使用命令行选项(例如)执行应用程序时Barcelona,将其传递给City对象而不引入中间参数?

在程序执行期间的不同阶段创建对象。

我们应该做 name变量设为静态还是使用IoC(例如Spring或Google Guice)?还有其他选择吗?

任何想法都欢迎。

Chr*_*bek 2

  • 我最喜欢 IOC 来完成这项任务。让国际奥委会在建设城市时传递依赖关系。
  • 替代方案:使用静态服务注册表,可以查询该服务注册表的值。城市的名称可以从服务登记处获得。
  • 替代方案:在您的层次结构上实现复合模式,包括诸如 find 之类的函数,该函数可以返回城市。然后你只需要查询和设置earth.find(BarcelonaID).setName(args[0]);

PicoContainer 中的 IoC 解决方案的示例如下:

PicoContainer container = new DefaultPicoContainer();
container.addComponent(Earth.class);
container.addComponent(Continent.class);
container.addComponent(Country.class);
container.addComponent(City.class, new ConstantParameter(cityName));

City barcelona = container.getComponent(City.class);
Run Code Online (Sandbox Code Playgroud)