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

问题描述

我有一个THIS类,该类显然对我创建的每个实例都是可变的,但是我想知道是否存在 某种包装器(或某种包装器)使该类的一个特定对象不可变。例如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;
    }
}

解决方法

我知道的唯一方法是实例化它,并覆盖能够修改特定实例的方法:

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");
    }
};

这也满足了仅该类的一个特定实例具有特殊行为的条件。


如果您需要更多它们,请创建一个包装类,将其充当装饰器(并非完全如此)。 别忘了,将类设为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");
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...