用于将类转换为另一个类的设计模式 [英] Design pattern to convert a class to another
问题描述
我有一个名为GoogleWeather的类,我想将其转换为另一个类CustomWeather。
I have a class called GoogleWeather, I want to convert it to another class CustomWeather.
是否有任何设计模式可以帮助您转换类?
Is there any design pattern which helps you to convert classes?
推荐答案
有一个关键决定要做:
你们需要转换生成的对象来反映未来对源对象的更改吗?
如果您不需要这样的功能,那么最简单的方法是使用具有静态方法的实用程序类,该方法基于源对象的字段创建新对象,如其他答案中所述。
If you do not need such functionality, then the simplest approach is to use a utility class with static methods that create a new object based on the fields of the source object, as mentioned in other answers.
另一方面,如果你需要转换的对象来反映对源对象的更改,您可能需要适配器设计的内容。模式:
On the other hand, if you need the converted object to reflect changes to the source object, you would probably need something along the lines of the 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;
}
...
}
这篇关于用于将类转换为另一个类的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!