读书人

java之不可变对象一(immutable object

发布时间: 2012-12-18 12:43:41 作者: rapoo

java之不可变对象1(immutable objects in java)

an immutable object is an object whose state cannot be modified after it is created.

不可变对象一旦被创建就它的状态就不能被修改。

?

A classic example of an immutable object is an instance of the Java String class.

不可变对象的一个经典的例子是String类的实例。

?

String s = "ABC";s.toLowerCase();

?

The method toLowerCase() will not change the data "ABC" that s contains.

Instead, a new String object is instantiated(被实例化) and given the data "abc" during its construction.

A reference to this String object is returned by the toLowerCase() method.

To make the String s contain the data "abc", a different approach is needed.

?

s = s.toLowerCase();

?

Now the String s references a new String object that contains "abc". The String class's methods never affect the data that a String object contains.

?

?

?

For an object to be immutable, there has to be no way to change fields, mutable or not, and to access fields that are mutable.

Here is an example of a mutable object.

?

import java.util.ArrayList;import java.util.LinkedList;import java.util.List;class Cart {private final List items;public Cart(List items) {this.items = items;}public List getItems() {return items;}public static void main(String[] args) {List list = new ArrayList();list.add("element1");Cart cart = new Cart(list);cart.getItems().add("element2");// 下面的代码能运行吗?为什么// list=new LinkedList();// cart.items=list;}}
?

An instance of this class is not immutable: one can add or remove items either by obtaining the field items by calling getItems() or by retaining(保留,保持) a reference to the List object passed when an object of this class is created.

?

The following change partially solves this problem. In the ImmutableCart class, the list is immutable: you cannot add or remove items.

However, there is no guarantee that the items are also immutable.

One solution is to use the decorator pattern as a wrapper around each of the list's items to make them also immutable.

?

import java.util.ArrayList;import java.util.Collections;import java.util.List;class ImmutableCart {private final List items;public ImmutableCart(List items) {this.items = Collections.unmodifiableList(new ArrayList(items));}public List getItems() {return items;}public static void main(String[] args) {List list = new ArrayList();list.add("element1");ImmutableCart cart = new ImmutableCart(list);cart.getItems().add("element2");}}

?运行抛出异常:

Exception in thread "main" java.lang.UnsupportedOperationException

?

?

?

?

?

?

读书人网 >编程

热点推荐