lundi 12 juin 2017

Standard practice of workaround to extend 2 classes in Java

This is the scenario

Interface BaseMsg
Interface SpecialMsg

class FooBaseMsg implements BaseMsg
class FooSpecialMsg extends FooBaseMsg implements SpecialMsg

// The above classes are written by another team, and cannot be modified. 

class BarBaseMsg implements BaseMsg // totally different way to implement
class BarSpecialMsg // this is the question

Methods implemented for SpecialMsg in FooSpecialMsg is totally the same as in BarSpecialMsg.

So it is really bad practice to copy-paste the implementations

But methods for BaseMsg is different.

My current approach is

class BarSpecialMsg extends BarBaseMsg implements SpecialMsg
  private FooSpecialMsg foo;
  // constructors will have super(), and initialize FooSpecialMsg
  // implements methods from SpecialMsg by calling
  // foo.methods()

Is this the correct way to do it? What are the standards for this kind of problem?

Is there some sort of design pattern to counter this?

The down-side of current approach is that the data is duplicated since it uses resources for 2 objects for every usage

Aucun commentaire:

Enregistrer un commentaire