불변 객체
배경
일반적인 불변 객체
class ImmutablePerson {
private final int age;
private final int name;
public ImmutablePerson(int age, int name) {
this.age = age;
this.name = name;
}
}
참조 타입이 있는 경우
public class Animal {
private final Age age;
public Animal(final Age age) {this.age = age;}
public Age getAge() {return age;}
}
class Age {
private int value;
public Age(final int value) {this.value = value;}
public int getValue() {return value;}
}
Array일 경우
public class ArrayObject {
private final int[] array;
public ArrayObject(final int[] array) {
this.array = Arrays.copyOf(array,array.length);
}
public int[] getArray() {
return (array == null) ? null : array.clone();
}
}
List인 경우
public class ListObject {
private final List<Animal> animals;
public ListObject(final List<Animal> animals) {
this.animals = new ArrayList<>(animals);
}
public List<Animal> getAnimals() {
return Collections.unmodifiableList(animals);
}
}