Search code examples
javaoopobjectdesign-patternsobject-oriented-analysis

Object-oriented design pattern for object converter


I was wondering what the best OOP design pattern should be put in place for my scenario.

The scenario:

I have two classes, ClassA & ClassB. I want to convert ClassA into a new ClassB, however, ClassA may change its member variables & methods. This means that one may have to update the way ClassA is translated into ClassB.

What would be the best OOP design to go about facilitating this translation from ClassA to a new ClassB?

The goal:

Create a design pattern that will allow to easily change the way ClassA will be translated to ClassB.

Example:

ClassA

public class ClassA {
    private String actionName;

    // With some getters & setters
}

ClassB

public class ClassB {
    private String action; // Note the subtle difference

    // With some getters & setters
}

Handler

public class Handler {
    ClassB classB = new ClassB();

    // Convert ClassB to ClassA

    This.publish(ClassA);
}

Solution

  • You need a type that has a knowledge of all the members of both ClassA and ClassB. It is a bad idea to couple either ClassA or ClassB to each other, so you would normally see a third type that implements an interface like this:

    interface Converter<T, R> {
      R convert(T obj);
    }
    

    You could implement this interface for your classes:

    class AtoBConverter implements Converter<ClassA, ClassB> {
      public ClassB convert(ClassA obj) {
        ...
      }
    }
    

    This assumes that ClassA has public methods that allow you to examine its state and ClassB has a constructor/setters that allow you to modify its state. Strictly speaking if all three classes are in the same java package you could have those methods/constructors declared package private.