2012-08-06 48 views
28

我有一個名爲GoogleWeather的類,我想將它轉換爲另一個類CustomWeather。將類別轉換爲另一類別的設計模式

有什麼設計模式可以幫助你轉換類嗎?

+0

裝飾模式? – assylias 2012-08-06 16:17:27

+0

什麼是您的層次結構(CustomWeather是否擴展了GoogleWeather)? 「轉換」是什麼意思? – Flawyte 2012-08-06 16:17:45

+0

轉換如何?創建一個子類,重命名它等?目前還不清楚您在「CustomWeather」類中的要求 – russ36363 2012-08-06 16:18:09

回答

34

有一個關鍵的決定,使:

是否需要由該轉換生成反映到源對象未來變化的對象?

如果您不需要這樣的功能,那麼最簡單的方法是使用靜態方法的實用程序類,該方法根據源對象的字段創建新對象,如其他答案中所述。

在另一方面,如果你需要轉換的對象,以反映更改源對象,你可能需要沿Adapter design pattern線的東西:

public class GoogleWeather { 
    ... 
    public int getTemperatureCelcius() { 
     ... 
    } 
    ... 
} 

public interface CustomWeather { 
    ... 
    public int getTemperatureKelvin(); 
    ... 
} 

public class GoogleWeatherAdapter implements CustomWeather { 
    private GoogleWeather weather; 
    ... 
    public int getTemperatureKelvin() { 
     return this.weather.getTemperatureCelcius + 273; 
    } 
    ... 
} 
+0

我不明白適配器和映射器appproche之間的區別使用在這種情況下的適配器模式? – user1549004 2012-08-06 21:34:22

+2

@ user1549004:適配器是一個包裝器 - 所有方法都被轉發到源對象。這意味着對源對象的任何更新都會通過適配器傳播。另一方面,使用映射類是一次性的 - 任何對源的更新通常都不會影響轉換的結果。 – thkala 2012-08-06 21:46:05

+0

可以請你給我一個例子,當使用一個映射類的情況下,任何更新來源不會影響轉換的結果。 – user1549004 2012-08-06 22:04:06

37

在這種情況下,我會使用一個映射器類有一堆的靜態方法:

public final class Mapper { 

    public static GoogleWeather from(CustomWeather customWeather) { 
     GoogleWeather weather = new GoogleWeather(); 
     // set the properties based on customWeather 
     return weather; 
    } 

    public static CustomWeather from(GoogleWeather googleWeather) { 
     CustomWeather weather = new CustomWeather(); 
     // set the properties based on googleWeather 
     return weather; 
    } 
} 

所以你不必類之間的依賴關係。

使用範例:

CustomWeather weather = Mapper.from(getGoogleWeather()); 
+1

與Mapper一起使用是否合適? – user1549004 2012-08-06 16:23:10

+4

因爲,它是**有史以來最好的方法**! (只是在開玩笑,但嘿,我不會在這裏推薦不好的解決方案) – 2012-08-06 16:24:20

+2

應該注意的是:這是一次性轉換;源對象的將來更改不會影響生成對象的字段。 – thkala 2012-08-06 19:45:05

相關問題