设计模式将类转换为另一个

时间:2012-08-06 16:15:32

标签: java

我有一个名为GoogleWeather的类,我想将其转换为另一个类CustomWeather。

是否有任何设计模式可以帮助您转换类?

3 个答案:

答案 0 :(得分:51)

在这种情况下,我会使用Mapper类和一堆静态方法:

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 :(得分:42)

要做出一个关键决定:

您是否需要转换生成的对象以反映未来对源对象的更改?

如果您不需要此类功能,那么最简单的方法是使用具有静态方法的实用程序类,该方法基于源对象的字段创建新对象,如其他答案中所述。

另一方面,如果您需要转换的对象来反映对源对象的更改,您可能需要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;
    }
    ...
}

答案 2 :(得分:5)

此外,您还可以使用java.util.function'中的新Java8功能'Function'。

http://www.leveluplunch.com/java/tutorials/016-transform-object-class-into-another-type-java8/中提供了更详细的说明。请看看!