2016-11-25 62 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); 
    } 
}