首页 > 解决方案 > 在抽象类中初始化最终字段的最佳方法

问题描述

我想到了两种方法来初始化抽象类中的 final 字段,我必须选择最优雅、正确和其他开发人员可以理解的方法。我的抽象类将至少有 10 个实现。关于我应该选择哪一个的任何想法?

第一种方式:

public sealed abstract class GuiComponent permits DummyComponent {

    private final Node internalNode;

    //------Constructor

    protected GuiComponent() {
        internalNode = Objects.requireNonNull(initInternalNode());
    }

    //------Protected

    protected abstract Node initInternalNode();

    protected final Node getInternalNode() {
        return internalNode; //subclasses will use this
    }

}

public final class DummyComponent extends GuiComponent {

    @Override
    protected Node initInternalNode() {
        HBox hbox = new HBox();
        //some Node preparation
        return hbox;
    }

}

第二种方式:

public sealed abstract class GuiComponent permits DummyComponent {

    private final Node internalNode;

    //------Constructor

    protected GuiComponent(Node internalNode) {
        this.internalNode = Objects.requireNonNull(internalNode);
    }

    //------Protected

    protected final Node getInternalNode() {
        return internalNode; //subclasses will use this
    }

}

public final class DummyComponent extends GuiComponent {

    //------Constructor

    public DummyComponent() {
        super(initInternalNode());
    }

    //------Private

    private static Node initInternalNode() {
        HBox hBox = new HBox();
        //...
        return hBox;
    }

}

标签: javajavafx

解决方案


在我看来,第二种方法更好。原因是GuiComponent构造函数请求 a Node,因此更容易理解 aNode实际上是需要的。这使它显式,而另一种方法使它隐式,因为除非您看到GuiComponent代码,否则您无法知道该getInternalNode()方法将在GuiComponent构造函数中调用。你甚至可以说它是这个构造函数的副作用,因为我们都知道在软件开发中通常最好避免副作用。


推荐阅读