不变类中的对象作为成员变量 [英] Objects in an immutable class as member variable
问题描述
我有一个X类,其中包含Employee对象.我想使X类不可变.现在,即使我将Employee对象声明为final,Employee类也独立存在,并且人们可以访问该特定employee对象的setter方法.可以有一个普通的Employee类,另一个拥有Employee的不可变类X,但是一旦分配了Employee,我们就不能更改它的值?
I have a class X which holds Employee object. I want to make the class X as immutable. Now even if I declare the Employee object as final the Employee class exists independently and people can access the setter methods of that particular employee object. Is it possible to have a normal class Employee and another immutable class X which holds Employee but we cannot change value of Employee once it is assigned?
public final class X {
private final Employee emp;
public X (Employee e){
this.emp = e;
}
public Employee getEmp(){
return emp;
}
}
我不想使它成为不可变的雇员类别,只想使X类成为不可变的.因此,一旦分配了雇员,就不应对其进行更改. 在不使Employee类不变的情况下可行吗? 我希望让Employee类独立存在,所以不想私有化其构造.
The employee class I dont want to make it immutable, just want to make the class X as immutable.Hence once an employee is assigned it should not be allowed to change it. Is that possible without making the class Employee as immutable. I want class Employee to exist independently so do not want to privatize its construction.
推荐答案
您不必公开不可变类的Employee成员.您可以引入仅公开Employee相关字段的getter方法.
You don't have to expose the Employee member of the immutable class. You can introduce getter methods that would expose only relevant fields of the Employee.
public final class X {
private final Employee emp;
public X (Employee e){
this.emp = e.clone ();
}
public String getEmpName(){
return emp.getName();
}
public int getEmpSalary(){
return emp.getSalary();
}
}
当然,您还有另一件事要做,以确保该类确实是不可变的.构造函数应创建传递给它的Employee的副本.否则,构造函数的调用者仍然可以引用Employee,并且可以更改该对象.
Of course, there's one more thing you have to do to ensure the class is really immutable. The constructor should create a copy of the Employee passed to it. Otherwise, the caller of the constructor would still have a reference to the Employee, and would be able to change that object.
这篇关于不变类中的对象作为成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!