user2957954 user2957954 - 1 year ago 44
Java Question

Which design pattern to use (if exists)?

I have a question about OOP implementation and design patterns.

I have a fixed class model which I cannot change (because it is generated automatically each time the application starts). There are many classes there with equals fields like in example below: as you can see the fields

city
and
streets
are contained in the both classes.

public class A{
String city;
String street;

String name;

....//get methods
}

public class B{
String city;
String street;

String age;

....//get methods
}


I need to extract an address form the both types of classes and I want to implement it with one method (because it seems to be silly to write the same code twice). If the class model were changeable, I could add a new interface
Addressable
which
A
and
B
could implement.

public interface Addressable{

public String getStreet();
public String getCity();
}

//somewhere in code
public Address getAddress(Addressable addressable){
return new Address(addressable.getCity(), addressable.getStreet());
}


What is the most elegant way to implement the same without interface and without coding the same for different classes?

Answer Source

If you are not able to change A or B, you would have necessarily a degraded solution.
A simple and good designed solution would rely of course on a interface defining an Address retrieval method (Address getAddress()) that A and B would implement.

You could also define a wrapper class :

public class WrapperA implements Addressable {

  private final A a;

  public WrapperA(A a) {
    this.a = a;
  }

  @Override
  public Address getAddress(){
     return new Address(a.getCity(), a.getStreet(), etc...);
  } 

}

But it may be rather clumsy if you have to duplicate this kind code for many classes.
Besides the client will not manipulate any longer a A but a WrapperA class.
It may break the actual client code.
So also here, an interface is required if you want to implement a real adapter.

As said, without redesigning a minimum A or B, a really good solution is complicated.


As workaround, you may define an Address class that provides factory methods to create Address from a A or a B instance.

public class Address{

    ... 
   String city;
   String street;
    ... 

   private Address(){
   }

   public static Address of(A a){
     return new Address(a.getStreet(), a.getCity(), ....);
   }

   public static Address of(B b){
     return new Address(b.getStreet(), b.getCity(), ...);
   }

}

Then use these methods to create the Address on the demand as you need it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download