khateeb
khateeb

Reputation: 5469

Alternate design for multiple inheritance

My program takes data from different file types and inserts them into different DBs depending on the department which uploaded the file.

To accomplish this, I have a base abstract class AbstractHandler which has some methods which are unimplemented and some which are common to all children. Two types of abstract classes extend from this class, InputTypeAHandler, InputTypeBHandler, etc. and OutputTypeAHandler, OutputTypeBHandler, etc. These abstract classes also implement some more methods but not all.

I have concrete classes which I want to extend from these two types of classes and which will implement some more methods specific to every class. For example,

abstract class AbstractHandler {
  public void method1() {
    // ....
  }
  public abstract void method2();
  public abstract void method3();
  public abstract void method4();
}
abstract class InputTypeAHandler extends AbstractHandler {
  @Override
  public void method2() {
    // ....
  }
}
abstract class OutputTypeBHandler extends AbstractHandler {
  @Override
  public void method3() {
    // ....
  }
}

public class ConcreteHandler1 extends InputTypeAHandler, OutputTypeBHandler {
  @Override
  public void method4() {
    // ....
  }
}
public class ConcreteHandler2 extends InputTypeCHandler, OutputTypeAHandler {
  @Override
  public void method4() {
    // ....
  }
}

Since Java does not allow multiple inheritance, how do I do this?

Upvotes: 0

Views: 68

Answers (2)

You seem to implement some kind of conversion between any pair of A,B,C... types (perhaps formats?). If it is the case, the AbstractHandler probably has multiple responsibilities. Split its logic to part involving source format and part involving target format. You can inspire in converter pattern or GoF Bridge pattern.

Upvotes: 2

Julian Kreuzer
Julian Kreuzer

Reputation: 356

I use lombok and the power of interfaces for this:

public class Test implements InputTypeAHandler,OutputTypeAHandler {
    @Delegate
    OutputTypeAHandlerImp outputTypeAHandlerImp = new OutputTypeAHandlerImp() {
      @Override
      String id() {
        return "mellow";
      }
    };
    @Delegate
    InputTypeAHandlerImp inputTypeAHandler = new InputTypeAHandlerImp(){
      @Override
      String id() {
        return "hello124";
      }
    };
    
  }


  public static abstract class OutputTypeAHandlerImp implements OutputTypeAHandler {

    abstract String id();
    
    @Override
    public void write(String s) {
      System.out.println(s);
    }
  }
  
  public static abstract class InputTypeAHandlerImp implements InputTypeAHandler {
    abstract String id();
    
    @Override
    public String read() {
      return new Scanner(System.in).nextLine();
    }
  }
  
  public interface InputTypeAHandler {
    String read();
  }

  public interface OutputTypeAHandler{
    void write(String s);
  }

Upvotes: 1

Related Questions