简体   繁体   中英

Inheritance in Java (design pattern)

I'm refactoring some code, abstracting functionality from a subclass to a helper class, but I found that I need methods from the superclass in the helper class.

I was wondering if there is a design pattern that can help me to do this. Or any other suggestions.

public class Notification(){
    public void printMessage(String k, String str){
        //Some code
    }
}

public class NotificationImpl1 extends Notification(){
    ErrorHelper helper = new ErrorHelper();
    helper.showMessage("test");
}

public class ErrorHelper(){
    public void showMessage(String msg){
        // need to call printMessage() here
    }
}

Thanks in advance.

public class ErrorHelper(){

  Notification notification = null;

  public ErrorHelper(Notification notification){
    this.notification = notification;
  }

  public void showMessage(String k_str, String msg){
    this.notification.printMessage(k_str, msg);
    // need to call printMessage() here
  }
}
public class Notification(){
   public void printMessage(String k, String str){
      //Some code
   }
}

public class NotificationImpl1 extends Notification(){
     public void method1() {
          ErrorHelper helper = new ErrorHelper();
          helper.showMessage("test", this);
     }
}

public class ErrorHelper() {
    public void showMessage(String msg, Notification notification){
       // Change msg to necessary 2 parameters.
       String k = getK(msg);
       String str = getStr(msg);
       notification.printMessage(k, str);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM