java—给定一个可变类,如何使该类的特定对象不可变?

zsbz8rwp  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(348)

我得到的这个类对于我创建的每个示例来说都是可变的,但是我想知道是否有´它是某种 Package 器(或其他东西),使这个类的一个特定对象不可变。例如 Collections.unmodifiableList(beanList) .

class Animal {
    private String name;
    private String commentary;

    public Animal(String nombre, String comentario) {
        this.name = nombre;
        this.commentary = comentario;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return Objects.equals(name, animal.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    public String getName() {
        return name;
    }

    public String getCommentary() {
        return commentary;
    }

    public void setCommentary(String commentary) {
        this.commentary = commentary;
    }

    public void setName(String name) {
        this.name = name;
    }
}
q9yhzks0

q9yhzks01#

我知道的唯一方法是示例化它并重写能够修改特定示例的方法:

Animal animal = new Animal("name", "commentary") {

    @Override
    public void setCommentary(String commentary) {
        throw new UnsupportedOperationException("The Animal is immutable");
    }

    @Override
    public void setName(String name) {
        throw new UnsupportedOperationException("The Animal is immutable");
    }
};

这也满足了只有一个类的特定示例具有特殊行为的条件。
如果您需要更多的,可以创建一个 Package 类来充当装饰器(不完全是)。别忘了把课堂布置成 final 否则,您将能够以我上面描述的方式重写它的方法,并且它的不变性可能会中断。

Animal animal = new ImmutableAnimal(new Animal("name", "commentary"));
final class ImmutableAnimal extends Animal {

    public ImmutableAnimal(Animal animal) {
        super(animal.getName(), animal.getCommentary());
    }

    @Override
    public void setCommentary(String commentary) {
        throw new UnsupportedOperationException("The Animal is immutable");
    }

    @Override
    public void setName(String name) {
        throw new UnsupportedOperationException("The Animal is immutable");
    }
}

相关问题