mardi 4 octobre 2016

Multiple inheritance with generic in Java

I'm trying to clean up my code using Design Patterns, however this is my weakness. Below is my situation and my current design, it has a lot of duplicate code.

SingleParent1 has 4 sub-classes, each one has it own way to manipulate the variable current in method computeValue. SingleParent2 has no sub-class and no other method.

Similarly, ArrayParent1 also has 4 sub-classes like SingleParent1, the code of method computeValue can be cloned from that of SingleParent1 and its children. ArrayParent2 has no sub-class and no other method.

However, ArrayParent1 and ArrayParent2 has the method 'getValue' with exactly the same code, but they need to be 2 separate classes.

In summary getValue gets the value from a data structure. SingleParent1 and ArrayParent1 and their sub-classes need to maintain the data structure while SingleParent2 and ArrayParent2 do not need to do so.

How can I re-factor the classes to remove duplication? My question is for Java, "multiple inheritance" is just what I'm thinking.

public abstract class SuperClass <T>{

  abstract T getValue();
}

public class SingleParent1 extends SuperClass<Long>{
  long current;
  ...

  void computeValue(){
     // do something with current
  }

  Long getValue(){
    return current;
  }
}

public class SingleParent2 extends SuperClass<Long>{

  Long getValue(){
    // different from SingleParent1
  }
}

public class ArrayParent1 extends SuperClass<ArrayList<Long>>{
  long current;
  ...

  void computeValue(){
     // exactly the same as in SingleParent1
  }

  ArrayList<Long> getValue(){
    // 
  }
}

public class ArrayParent2 extends SuperClass<ArrayList<Long>>{

  ArrayList<Long> getValue(){
    // exactly the same as ArrayParent1
  }
}

Aucun commentaire:

Enregistrer un commentaire