我对使用Java的OO编程很新.我有一个关于继承的问题.
我有一个打印方法,我希望在子类中很常见. print方法中的代码可用于所有子类,但特定于每个子类的响应对象除外.
我想我可能只是覆盖每个子类中提供特定实现的方法.然而,感觉就像在超类中保持公共方法并且以某种方式基于访问它的子类提供特定响应对象一样.
有什么想法吗?对不起,如果这看起来很……
解决方法:
你是绝对正确的,还有更好的方法.如果您的实现共享大量代码,则可以使用template method pattern重用尽可能多的实现.
在超类中定义printReponse方法,并使其成为抽象方法.然后在执行常见事务的超类中编写print方法,并在需要时调用printResponse.最后,仅覆盖子类中的printResponse.
public abstract class BasePrintable {
protected abstract void printResponse();
public void print() {
// Print the common part
printResponse();
// Print more common parts
}
}
public class FirstPrintable extends BasePrintable {
protected void printResponse() {
// first implementation
}
}
public class SecondPrintable extends BasePrintable {
protected void printResponse() {
// second implementation
}
}
标签:java,oop
来源: https://codeday.me/bug/20190902/1790575.html