`
tomotoboy
  • 浏览: 162391 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

immutable object

    博客分类:
  • Java
阅读更多
Immutable objects

What is immutable object?
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

简言之:不可变对象就是在创建之后状态不可改变的对象,如String、Integer等。

Why Immuntable Objects?
Immutable objects greatly simplify your program, since they :
不可变对象最大程度上简化我们的程序,因为它们有如下优点:
  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
  • have their class invariant established once upon construction, and it never needs to be checked again
  • always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
不可变对象有一大堆的优点。毫无疑问,你可以用它构建极其简单、健壮的类。当你创建不可变类的时候,上面所提到的所有问题都没有了。

How to make an immutable class?

Make a class immutable by following these guidelines :
编写一个不可变的类要遵循以下原则:
  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private——类不能被覆盖或重写
  • make fields private and final——所有的成员必须由private和final修饰
  • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)——调用者只能一步完成对象的创建,不要使用无参构造哈数和setXXX相结合的构造方式来构造对象
  • do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state——不要提供任何可以改变对象状态方法,不仅仅是set方法,或者其它任何能够改变状态的方法。
  • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller ——如果类包含任何可变的对象,在类和它的调用者之间传递时必须拒绝复制。

让我们来一看String的一个例子
public class StringDemo {

	public void sayHello(String str){
		str = "Hello: "+str;		
	}
	
	
	public static void main(String[] args) {		 
		 
		 //String是不可变的,当它创建之后,它的值是不可以改变的
		 String str ="China";
		 new StringDemo().sayHello(str);
		 System.out.println(str);
		 String old_str;
		 old_str = str;		
		 
		 str = "Hello: "+str; /*str不在是原来String了,
		                                                                此操作等价于str = 
		                        new String("Hello: "+str.toString())*/
		 
		 //str与old_str为两个完全不相同的引用
		 //String objects are immutable they can be shared
		 
                    System.out.println("new str:" + str);
		 System.out.println("old str:" + old_str);
		 //线程安全的可变字符串序列,支持同步操作,可变类
		 StringBuffer strBuffer;		 
		//线程不安全的可变字符串序列,不支持同步操作,可变类
		 StringBuilder  strBuilder;
                   /*strBuffer与strBuilder是可变对象,留给有心的读者自己去实验*/		 
		 	 
		 
	}

}
输出:
China
new str:Hello: China
old str:China


参考文献:
  • http://www.javapractices.com/topic/TopicAction.do?Id=29
  • http://www-sop.inria.fr/everest/events/cassis05/Transp/poll.pdf




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics