在本文中,我们将定义在Java中创建不可变类并实现它的典型步骤。
在Java中创建不可变类的步骤
Java中不可变类的实现
class Address{ private String houseNumber; private String street; private String city; } class User{ private int id; private String name; private String email; private Address address; }-
假设上面有一个名为User的类,我们需要将其转换为Java中的Immutable类。让我们遵循规则,并在Java中将此User类转换为Immutable类。
final class User { private final int id; private final String name; private final String email; private final Address address; /* * To clone the 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); } public int getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } public Address getAddress() { /* * Getter method must return the reference of cloned object. */ return cloneAddress(address); } }
Java中的预定义不可变类
java.util.UUID
在Java中制作不可变类的好处
结论 在本文中,我们已经看到了如何在java中创建Immutable类。不可变类为我们提供了许多优势,并且最适合多线程环境。我们还学习了组成不可变类的规则及其好处。
感谢您阅读本文。
原文链接:http://codingdict.com