17 Kasım 2020 Salı

Immutable Nesne

Örnek
Şöyle yaparız
final class User {
  private final int id;
  private final String name;
  private final String email;
  private final Address address;
  
  private static Address cloneAddress(Address address) {
    return new ObjectMapper().convertValue(address, Address.class);
  }
  User(int id, String name, String email, Address address) {
    this.id = id;
    this.name = name;
    this.email = email;

    //Any field contains reference of any mutable object must be
    //initialized with the cloned object
    this.address = cloneAddress(address);
  }
  //Normal getters for int and String
  public Address getAddress() {
    //Getter method must return the reference of cloned object.
    return cloneAddress(address);
  }
}

Hiç yorum yok:

Yorum Gönder