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
分享到:
相关推荐
#ImmutableObject ImmutableObject 被创建为一种简单的客户端 Javascript 方式来制作不可变对象。 它使用一组简单的方法来获取和设置项目。 仅当您为isExtensible传递true参数时才允许设置项目。 ##基本用法: 可以...
这是关于不可变对象模式的初学者教程,其中包含C#中的示例。我们讨论“内部不变性”与“观察不变性”等主题。
节点不变对象 imobject允许您创建深度不可变JavaScript对象。 设置属性后,将无法添加其他属性,并且无法修改初始属性。...var immutable = new IMObject({ foo: 'bar', nested: { foo: 'baz' } }); //
深拷贝&浅拷贝总结非集合对象[immutableObject copy]是浅拷贝[immutableObject mutableCopy]是深拷贝[mutabl
Why Mutable and Immutable Object Variants? 90 Programming with Mutable Objects 91 Class Clusters 95 Without Class Clusters: Simple Concept but Complex Interface 95 With Class Clusters: Simple Concept ...
4. 对于immutable object,计算结果如果已经存在可直接返回相同的identity 4. 注意:链式执行 1. 之所以要实现special met
npm install immutable-object-methods --save用法import { getIn , setIn , mergeDeep , assign , set , without , chain } from 'immutable-object-methods' ;const input = { a : { b : 'c' } } ;const updated ...
流行的Java面试题之一是:什么是不可变对象(immutable object),不可变对象有什么好处,在什么情况下应该用,或者更具体一些,Java的String类为什么要设成immutable类型? 不可变对象,顾名思义是创建后不可以...
Immutable Object模式: Two-phase Termination模式: 【前言】 随着现代CPU的生产Craft.io从提升CPU主频频率转向多核化,即在一块芯片上集成多个CPU内核(Core),以往那种靠CPU自身处理能力的提升所带来的软件计算...
前端开源库-immutable-require-valid-optional-object不可变要求有效的可选对象,如果参数不是对象,则返回空对象或引发异常
语言:English 将不可变JS对象记录到控制台时,使其更具...基于Immutable DevTools:https://github.com/andrewdavey/immutable-devtools源代码:https://github.com/mattzeunert/immutable-object-formatter-extension
npm install object-path-immutable --save 快速使用 下面,设置属性而不修改原始对象。 它将最大限度地减少线下的克隆数量。 生成的对象只是普通的JS对象文字,因此请注意,它将不会受到属性突变(例如Immutable.js...
Mkaes不可变JS对象登录到控制台时更易读。 将已记录的不可变JS对象转换为更易读的格式。 要使用扩展程序,您需要在...源代码:https://github.com/mattzeunert/immutable-object-formatter-extension 支持语言:English
主要介绍了Java进阶教程之String类,String类对象是不可变对象(immutable object),String类是唯一一个不需要new关键字来创建对象的类,需要的朋友可以参考下
of immutable code — names may change but not the structures. Therefore, in chapter seven we build a small preprocessor to create the boilerplate required. It looks like yet another new object-...
不变的对象 如何构建和使用不可变对象的示例。 文章解释代码: :
这个库实现了 3 个辅助函数: get(object, path) -- > valueset(object, path, value) -- > objectdelete(object, path) -- > object 没有一个函数会改变输入对象。 为了效率,返回的对象不是原始对象的深克隆,...
@ polyn / immutable使用本机JavaScript功能(即Object.freeze )使对象不可变。 它使用来验证您定义的架构,并且还支持自定义验证器(即,如果您更喜欢JSON架构)。 与Object.freeze不同,@ polyn / immutable递归...
var object = Immutable . fromJS ( { baz : 'qux' , foo : 'bar' } ) ;var patched = patch ( object , [ { op : 'replace' , path : '/baz' , value : 'boo' } , { op : 'add' , path : '/hello' , value : [ '...
immutable_object = restack(immutable_object) 将immutable_object放入堆栈中并避免这种性能陷阱。 当这种对象跨越非内联函数调用边界时,似乎倾向于发生这种情况。 另见, 和话语的讨论,也是这个古老PR 。 例 ...