2016-11-25 61 views
0

我重构了一些代码,从一个子类抽象为一个辅助类的功能,但我发现我需要帮助类中的超类的方法。在Java中的继承(设计模式)

我想知道是否有一种设计模式可以帮助我做到这一点。或者其他任何建议。

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 
    } 
} 

在此先感谢。

+0

一个可能的解决方案是声明子类错误帮手NotificationImpl1之外,只是添加扩展通知上课ErrorHelper这将给你访问父的所有功能,或者如果它只是一个小代码量只需复制并粘贴所需的方法即可。 – holycatcrusher

回答

2
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 
    } 
} 
+1

我也同意这个解决方案。 – holycatcrusher

0
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); 
    } 
}