我对面向对象编程(OOP)实现和设计模式有疑问。
我有一个固定的类模型,我无法更改它(因为每次应用程序启动时都会自动生成)。那里有许多类,就像下面的例子一样,有相同的等值字段:如您所见,city
和 streets
字段都包含在这两个类中。
public class A{
String city;
String street;
String name;
....//get methods
}
public class B{
String city;
String street;
String age;
....//get methods
}
我需要从这两种类型的类中提取地址,并且想用一个方法来实现它(因为重复编写相同的代码看起来很愚蠢)。如果类模型是可变的,我可以添加一个新的接口Addressable
,A
和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());
}
没有使用接口并且不需要为不同的类编写相同的代码,最优雅的实现方式是什么?