The best way to pass Java reference down the chain of objects

java, parameter-passing

Solution

- I like IOC best for this task. Let the IOC pass the dependency when it constructs the City.

- Alternative: Use a static service registry, which can be queried for a value. The City could get its name from the service registry.

- Alternative: Implement the Composite Pattern on your hierarchy, including a function such as find, which could return the City. Then you just have to query and set `earth.find(BarcelonaID).setName(args[0]);`

An example of how a IoC solution in PicoContainer would look like:

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);

Problem

Let's consider a chain of objects like this: ``` Earth->Continent->Country->City->name ``` Let's also consider `Earth.class` has `public static void main(String[] args)` When the application is executed with command-line option e.g. `Barcelona`, what would be the best way to pass it down to `City` object without introducing intermediate parameters? Objects are created at different stages during program execution. Should we make `name` variable static or use IoC such as Spring or Google Guice? Are there other options? Any ideas are welcome.

Original source