46
votes

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?

3
What is your hierarchy (does CustomWeather extends GoogleWeather) ? What do you mean by "converting" ?flawyte
Convert as in how? Creating a subclass, renaming it, etc? It's unclear what you desire in the "CustomWeather" classr36363
there is no inheritance between GoogleWeather and CustomWeatheruser1549004

3 Answers

63
votes

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());
56
votes

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;
    }
    ...
}
8
votes

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!