在java中使类不可变 [英] making a class immutable in java

查看:109
本文介绍了在java中使类不可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使一个类不可变,我能做的是:

To make a class immutable what I can do is:

1)使类最终

2)不提供setter

3)将所有变量标记为final

1)Make class final
2)do not provide setters
3)mark all variables as final

但是如果我的类有另一个类的其他对象那么,somone可以更改该对象的值

But if my class has another object of some other class then , somone can change value of that object

class MyClass{
 final int a;
 final OtherClass other 

 MyClass(int a ,OtherClass other){
  this.a = a;
  this.other = other;
 }

 int getA(){
   return a;
 }

 OtherClass getOther(){
   return other;
 }

 public static void main(String ags[]){
  MyClass m = new Myclass(1,new OtherClass);
  Other o = m.getOther();
  o.setSomething(xyz) ; //This is the problem ,How to prevent this?

}
}


推荐答案

A)使 OtherClass 不可变

B)不允许直接访问 OtherClass 对象,而只提供getter充当代理。

B) Don't allow direct access to the OtherClass object, instead providing only getters to act as a proxy.

编辑添加:可以制作 OtherClass的深层副本并返回一个副本而不是原始副本,但这通常不是您在Java中所期望的行为类型。

Edit to add: You could make a deep copy of OtherClass and return a copy rather than the original, but that generally isn't the type of behavior you would expect in Java.

这篇关于在java中使类不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆