简体   繁体   English

不变类中的对象作为成员变量

[英]Objects in an immutable class as member variable

I have a class X which holds Employee object. 我有一个X类,其中包含Employee对象。 I want to make the class X as immutable. 我想使X类不可变。 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. 现在,即使我将Employee对象声明为final,Employee类也独立存在,并且人们可以访问该特定employee对象的setter方法。 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? 是否可以有一个普通类Employee和另一个持有Employee的不可变类X,但是一旦分配了Employee我们就不能更改它的值?

public final class X {

private final Employee emp;

public X (Employee e){
   this.emp = e;

}
public Employee getEmp(){

return emp;

}

} 

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. 我不想使它成为不可变的雇员类,只想使X类成为不可变的。因此,一旦分配了雇员,就不应该对其进行更改。 Is that possible without making the class Employee as immutable. 在不使Employee类不变的情况下可行吗? I want class Employee to exist independently so do not want to privatize its construction. 我希望班级员工独立存在,所以不想私有化其构造。

You don't have to expose the Employee member of the immutable class. 您不必公开不可变类的Employee成员。 You can introduce getter methods that would expose only relevant fields of the Employee. 您可以引入仅公开Employee相关字段的getter方法。

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();
  }

} 

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. 构造函数应创建传递给它的Employee的副本。 Otherwise, the caller of the constructor would still have a reference to the Employee, and would be able to change that object. 否则,构造函数的调用方仍将具有对Employee的引用,并且能够更改该对象。

You could add an copy constructor to Employee and use it whenever an instance of it is passed into or out of your immutable class. 您可以向Employee添加一个复制构造函数,并在将其实例传入或传出不可变类时使用它。

public final class X {

    private final Employee emp;

    public X (Employee e){
       this.emp = new Employee(e);

    }
    public Employee getEmp(){
      return new Employee(emp);
    } 
} 

Having said this, you should still seriously re-evaluate if you better would make Employee immutable, too, as all this copying could have quite some overhead. 话虽如此,您仍然应该认真地重新评估是否更好地使Employee不可变,因为所有这些复制可能会产生相当大的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM