Which design template to use (if any)?

I have a question about implementation and OOP design patterns.

I have a fixed class model that I cannot change (because it is generated automatically every time the application starts). There are many classes with equal fields, as in the example below: As you can see, that the fields cityand streetscontained in 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 the address form for both types of classes, and I want to implement it with one method (because it seems silly to write the same code twice). If the class model was mutable, I could add a new interface Addressablethat could implement Aand B.

public interface Addressable{

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

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

?

+4
3

A B, .
, , , (Address getAddress()), A B.

:

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...);
  } 

}

, .
, A, a WrapperA.
.
, , .

, A B, .


Address, factory Address A B.

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(), ...);
   }

}

.

+3

, .

public class AdpaterA implements Addressable {

  private final A a;

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

  @Override public String getStreet() {
    return this.a.street;
  }

  // other method is omitted as homework ;-)
}

.

+2

, . ( .)

, . , , , . Linux, sed ant script.

0

Source: https://habr.com/ru/post/1683800/


All Articles