是否可以在创建对象后使其成为不可变对象

时间:2018-05-30 16:07:27

标签: java

我正在创建一个对象:

public class Car {

    private ArrayList<Door> doors;
    private Engine engine;

    public Car(ArrayList<Door> doors) {
        this.doors = doors;
    }

    public Car setDoors(ArrayList<Door> doors) {
        this.doors = doors;
        return this;
    }

    public Car setEngine(Engine engine) {
        this.engine = engine;
        return this;
    }// and getters
}

虽然它有公共setter,是否可以创建这个类的实例,然后在创建后使其不可变?

2 个答案:

答案 0 :(得分:1)

immutable是一个不可更改的对象,这意味着一旦创建它就无法更改其字段。基本上,您必须省略所有 setters 并将字段声明为final。将类声明为final可确保没有人可以从中继承。

public final class Car {

    private final List<Door> doors;
    private final Engine engine;

    public Car(final Engine engine, final List<Door> doors) {
        this.engine = engine;
        this.doors = doors;
    }

    // Getters ONLY
}

此示例确保该类不仅是不可变的,还是constant。我强烈建议您阅读有关Gradients of Immutability

的文章

答案 1 :(得分:0)

您可以检查成员变量的状态,如果它们尚未初始化,那么您可以允许设置者设置变量,否则在变量初始化后它们将不执行任何操作

public class Car {

    private ArrayList<Door> doors;
    private Engine engine;

    public Car() {
        this.doors = null;
        this.engine = null;
    }

    public Car(ArrayList<Door> doors) {
        this.doors = doors;
        this.engine = null;
    }

    public Car setDoors(ArrayList<Door> doors) {
        if(this.doors == null)
            this.doors = doors;
        return this;
    }

    public Car setEngine(Engine engine) {
        if(this.engine == null)
            this.engine = engine;
        return this;
    }// and getters
}