Java中的继承(设计模式)
我正在重构一些代码,将功能从一个子类抽象到一个helper类,但是我发现我需要helper类中的超类的方法 我想知道是否有一个设计模式可以帮助我做到这一点。或任何其他建议Java中的继承(设计模式),java,class,inheritance,Java,Class,Inheritance,我正在重构一些代码,将功能从一个子类抽象到一个helper类,但是我发现我需要helper类中的超类的方法 我想知道是否有一个设计模式可以帮助我做到这一点。或任何其他建议 public class Notification(){ public void printMessage(String k, String str){ //Some code } } public class NotificationImpl1 extends Notification(){
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
}
}
提前感谢。一个可能的解决方案是在NotificationImpl1之外声明子类Error helper,只需向类ErrorHelper添加extends通知,这将允许您访问父类的所有功能,或者,如果只是少量代码,只需复制并粘贴所需的方法。一种可能的解决方案是在NotificationImpl1之外声明子类Error helper,并向类ErrorHelper添加extends通知,这将使您能够访问父类的所有功能,或者,如果只是少量代码,只需复制并粘贴所需的方法。我也同意此解决方案。我也同意此解决方案。
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);
}
}