gpt4 book ai didi

java - 制作纯粹的不可变类

转载 作者:行者123 更新时间:2023-12-01 19:01:43 25 4
gpt4 key购买 nike

我有以下类(class):

Emp.java

final public class Emp {

private Integer id;
private String name;
private Department department;

public Emp(Integer id, String name, Department department) {
this.id = id;
this.name = name;
this.department = department;
}

public Department getDepartment() {
return department;
}

public Integer getId() {
return id;
}

public String getName() {
return name;
}
}

部门.java

public class Department {

private Integer id;
private String name;

public Department(Integer id, String name) {
this.id = id;
this.name = name;
}

public Integer getId() {
return id;
}

public String getName() {
return name;
}

public void setId(Integer id) {
this.id = id;
}

public void setName(String name) {
this.name = name;
}
}

EmployeeTest.java

public class EmployeeTest {

public static void main(String args[]) {
Department dept1 = new Department(1, "dept1");
Emp emp = new Emp(1, "emp1", dept1);
emp.getDepartment().setName("dept2");
System.out.println("emp = "+emp);

}
}

这里 Emp 类并不是纯粹的不可变类,因为我能够以某种方式更改 Department 的值(如示例所示)。

哪些可能的最佳更改将使 Emp 类成为纯 Immutable 类?

最佳答案

在非原始字段的getters中,使用此结构

public class Line {

private final Point start;
private final Point end;

public Line(final Point start, final Point end) {
this.start = new Point(start);
this.end = new Point(end);
}

public Point getStart() {
return new Point(start);
}

public Point getEnd() {
return new Point(end);
}
}

因此,只需创建与之前的部门相同的新部门实例

附注在我的示例中,您可以看到纯不可变类
编辑:
您还可以添加到 Department 类复制构造函数

public Department(final Department dep)  
{ ... }

致雇主

getDepartment()  
{
return new Department(department);
}

关于java - 制作纯粹的不可变类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12034894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com