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?
gson. Gson for converting one class object to another. First convert class A's object to json String and then convert Json string to class B's object.
An Adapter pattern acts as a connector between two incompatible interfaces that otherwise cannot be connected directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client's interface.
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With