Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern to convert a class to another [closed]

Tags:

java

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?

like image 420
user1549004 Avatar asked Aug 06 '12 16:08

user1549004


People also ask

How do you convert one model class to another model in Java?

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.

What is Adapter pattern used for?

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.

What design pattern would you use to make it easy to change the class of the object that a method returns?

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.

How do you convert one object to another in Java?

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.


1 Answers

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()); 
like image 116
Andreas Dolk Avatar answered Sep 28 '22 04:09

Andreas Dolk