【问题标题】:Given a mutable class, how to make immutable a specific object of this class?给定一个可变类,如何使这个类的特定对象不可变?
【发布时间】:2020-12-11 22:04:58
【问题描述】:

我得到了这个类,对于我创建的每个实例显然都是可变的,但我想知道是否有 某种包装器(或其他东西)使这个类的一个特定对象不可变。例如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;
    }
}

【问题讨论】:

  • 没有通用的方法可以做到这一点,除非你为这个特定的课程制作一个。这是因为无法知道类的哪些方法正在执行突变。

标签: java object design-patterns immutability access-modifiers


【解决方案1】:

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

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

【讨论】:

  • 抛出IllegalArgumentException很奇怪。
  • Collections.unmodifiableList(beanList) 返回一个不可修改的列表,但修改 beanList 也会修改该列表。 new ImmutableAnimal(anAnmial)返回的对象即使更改anAnimal也不会改变。
  • @saka1029:在我看来,这是第一个运行时异常。现在我觉得 UnsupportedOperationException 会更合适。它会改变答案的质量吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多