【问题标题】:Inheritance and static factory methods继承和静态工厂方法
【发布时间】:2016-03-29 13:00:07
【问题描述】:

我为我的控制台输出编写了一个 java.util.logging.Formatter(名为 OneLineFormatter)。它有两个静态工厂方法,都调用私有构造函数。

现在我想编写第二个用于调试目的(名为 DebugFormatter),它只覆盖 OneLineFormatter 中的方法 formatRecord,因此也打印了跟踪,而不仅仅是本地化消息和类。

Eclipse 警告我超级构造函数 OneLineFormatter() 未定义,我必须调用另一个构造函数。我用谷歌搜索了这个问题,发现:Java error: Implicit super constructor is undefined for default constructor 在 StackOverflow 上。 但我不想创建一个公共构造函数,因为这违反了工厂原则。工厂方法和构造函数可以相同(但 DebugFormatter 工厂方法应该创建一个新的 DebugFormatter 而不是 OneLineFormatter)。

如果您需要更多信息,请询问。提前感谢您的帮助!

代码:

public class OneLineFormatter extends Formatter {
    public static Formatter withPackageFromRoot(String rootName) {
        return new OneLineFormatter(rootName);
    }

    public static Formatter withClassOutputOnly() {
        return new OneLineFormatter("");
    }

    private String rootName;

    private OneLineFormatter(String rootName) {
        this.rootName = rootName;
    }

    @Override
    public String format(LogRecord record){<code>}

    private String formatRecord(LogRecord record{<code that I want to override>}
}

还有二等:

public class DebugFormatter extends OneLineFormatter {
    public static Formatter withClassOutputOnly() {
        return new DebugFormatter("");
    }

    public static Formatter withPackageFromRoot(String rootName) {
        return new DebugFormatter(rootName);
    }

    private DebugFormatter(String rootName) {<same as OneLineFormatter(String)>}

    @Override
    private String formatRecord(LogRecord record) {<code>} 

}

编辑 1:添加代码 编辑 2:更正的代码

【问题讨论】:

  • 请在问题中包含您的代码。没有它,仅通过阅读您的描述来分析哪里做错了会困难得多。
  • 我会从工厂拼接你的 OneLineFormater 代码。所以你可以扩展 OnlineFormater 而不是工厂。
  • @ReneM。工厂方法可以保持不变,我只想重写 OneLineFormatter 中的方法 formatRecord(LogRecord)
  • @KevinEsche 谢谢,添加代码
  • 您也可以只创建构造函数package-privateprotected。这样,您就可以在同一个包中或在每个子类中访问构造函数。

标签: java inheritance constructor factory-method


【解决方案1】:

您可以为OneLineFormatter package-privateprotected 创建构造函数。这样,您可以将对构造函数的访问减少到适合您需要的程度

OneLineFormatter(String rootName) {
    this.rootName = rootName;
}
// OR 
protected OneLineFormatter(String rootName) {
    this.rootName = rootName;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2016-10-06
    • 2023-04-05
    相关资源
    最近更新 更多