我有一个名为GoogleWeather的类,我想将它转换为另一个类CustomWeather。
是否有任何设计模式可帮助您转换类?
我有一个名为GoogleWeather的类,我想将它转换为另一个类CustomWeather。
是否有任何设计模式可帮助您转换类?
在这种情况下,我会使用一个带有一堆静态方法的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());
需要做出一个关键决定:
你是否需要从转换生成的对象反映源对象的未来更改?
如果不需要这样的功能,则最简单的方法是使用具有静态方法的实用程序类,该类基于源对象的字段创建一个新对象,如其他答案中所述。
另一方面,如果你需要转换后的对象反映源对象的更改,则可能需要类似于适配器设计模式的东西:
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;
}
...
}
int temperature = 30;
。使用映射器将会产生一个CustomWeather实例,并带有一个字段int temperature = 303;
。如果原始的GW实例在温度变化时被修改,例如变为32,那么转换后的CW实例仍然会保留旧值303,而不是更新为305。 - thkala