Design pattern to convert a class to another [closed]
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?
In that case I'd use a Mapper class with a bunch of static methods:
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;
}
}
So you don't have dependencies between the classes.
Sample usage:
CustomWeather weather = Mapper.from(getGoogleWeather());
There is one critical decision to make:
Do you need the object that is generated by the conversion to reflect future changes to the source object?
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;
}
...
}
Besides, You can also use new Java8 feature 'Function' from java.util.function'.
More detailed explanation is provided in http://www.leveluplunch.com/java/tutorials/016-transform-object-class-into-another-type-java8/ . Kindly have a look!