[英]The best way to pass Java reference down the chain of objects
讓我們考慮這樣的對象鏈:
Earth->Continent->Country->City->name
我們還要考慮Earth.class
具有public static void main(String[] args)
當使用命令行選項(例如Barcelona
)執行應用程序時,將其傳遞給City
對象而不引入中間參數的最佳方法是什么?
在程序執行期間的不同階段創建對象。
我們應該將name
變量設為靜態還是使用IoC(例如Spring或Google Guice)? 還有其他選擇嗎?
任何想法都歡迎。
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);
您可以從上至下(大陸構建城市,或從下至上)構建數據結構, main
從城市構建城市並將其傳遞給國家(或使用某種組合)。 DI贊成后者。
public static void main(String... argv) {
// Bottom up.
City city = new City(/* args relevant to city */);
Country country = new Country(city, /* args relevant to country */);
Continent continent = new Continent(country, /* args relevant to continent */);
Planet planet = new Planet(continent, /* args relevant to planet */);
}
class City {
City(/* few parameters */) { /* little work */ }
}
class Country {
Country(/* few parameters */) { /* little work */ }
}
...
class Planet {
Planet(/* few parameters */) { /* little work */ }
}
這比自上而下的要干凈得多:
public static void main(String... argv) {
// Top down.
Planet earth = new Planet(
/* all the parameters needed by Earth and its dependencies. */);
}
class Planet {
Planet(/* many parameters */) { /* lots of work */ }
}
...
DI人士堅持認為,自下而上的構造會導致可維護性和可測試性更高的代碼,但是您不需要DI框架即可使用它。
在我看來,這是您可以想到的“ 訪客”模式的最佳用例。 基本上,應該有一類Parameters
,其中應包含所有參數。 每個需要一組參數的對象都可以通過該Parameters
類進行訪問。 然后,對象可以將參數傳遞給知道使用哪些參數以及如何使用這些參數的子級。 就您而言,這可以通過以下方式完成:
public interface IParameterized{
public void processParameters(Parameters param);
}
public class Earth implements IParameterized{
public Earth(){
// Create all countries here and store them in a list or hashmap
}
public void processParameters(Parameters param){
// find the country you want and pass the parameters to it
country.processParameters(param);
}
}
public class Country implements IParameterized{
public Country(){
// Create all cities that belong to this country
}
public void processParameters(Parameters param){
// find the city you want and pass the parameters to it
city.processParameters(param);
}
}
public class City implements IParameterized{
public City(){
// Create city...
}
public void processParameters(Parameters param){
// Do something with the parameter
}
}
編輯要連接點,可以按以下方式使用:
public static void main(String... argv) {
Parameters params = new Parameters();
// Populate params from the command line parameters
Earth earth = new Earth();
// Earth takes the responsibilty of processing the parameters
// It will delegate the processing to the underlying objects in a chain
earth.processParameters(params);
}
作為旁注,您還可以查看“責任鏈”設計模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.