java 重构有状态类

9wbgstp7  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(109)

我在java中有一个有状态的类

class Container {
   int capacity;
   String name;
   
   public int getCapacity() {
        return capacity;
   }
   public void consumeContainer(int numberOfUnits) {
        this.capacity = this.capacity - numberOfUnits;
   }
}

我正在寻找重构这个类的方法,这样我就不必在每次容器被使用的时候都改变类。Maven们能提供一些想法吗?
谢谢

62lalag4

62lalag41#

如果你想让你的类不可变,这是一个选项:

class ImmutableContainer {
    final int capacity;
    final String name;
               
    public ImmutableContainer(int capacity, String name) {
        this.capacity = capacity;
        this.name = name;
    }
               
    public int getCapacity() {
        return capacity;
    }

    public ImmutableContainer consumeContainer(int numberOfUnits) {
        return new ImmutableContainer(this.capacity - numberOfUnits, name);
    }
}

或者,更简单地说,作为一个记录:

record ImmutableContainer(int capacity, String name) {

    public ImmutableContainer consumeContainer(int numberOfUnits) {
        return new ImmutableContainer(this.capacity - numberOfUnits, name);
    }
}

相关问题