Java实现Immutable Class要点[转帖]_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3512 | 回复: 0   主题: Java实现Immutable Class要点[转帖]        下一篇 
jfl
注册用户
等级:少校
经验:1112
发帖:95
精华:0
注册:2012-8-10
状态:离线
发送短消息息给jfl 加好友    发送短消息息给jfl 发消息
发表于: IP:您无权察看 2012-8-27 12:32:01 | [全部帖] [楼主帖] 楼主

Java中很多class都是immutable,像String,Integer等,它们通常用来作为Map的key.

那么在实现自定义的Immutable的Class的时候,应该注意哪些要点呢?

a)Class 应该定义成final,避免被继承。

b)所有的成员变量应该被定义成final。

c)不要提供可以改变类状态(成员变量)的方法。【get 方法不要把类里的成员变量让外部客服端引用,当需要访问成员变量时,返回成员变量的copy】

d)构造函数不要引用外部可变对象。如果需要引用外部可以变量,应该在构造函数里进行defensive copy。 达内好不好

[java] view plaincopyprint?

Wrong way to write a constructor:

public

final

class MyImmutable {

    private

    final

    int[] myArray;

    public MyImmutable(int[] anArray) {

    this.myArray = anArray; // wrong

    }

    public String toString() {

    StringBuffer sb = new StringBuffer("Numbers are: ");

    for (int i = 0; i < myArray.length; i++) {

    sb.append(myArray + " ");

    }

    return sb.toString();

    }

}

// the caller could change the array after calling the

constructor.

int[] array = {1,2};

MyImmutable myImmutableRef = new MyImmutable(array) ;

System.out.println("Before constructing " + myImmutableRef);

array[1] = 5; // change (i.e. mutate) the element

System.out.println("After constructing " + myImmutableRef);

Out put:

Before constructing Numbers are: 1

2

After constructing Numbers are: 1

5

Right way to write an immutable class

Right way is to copy the array before assigning in the constructor.

public

final

class MyImmutable {

    private

    final

    int[] myArray;

    public MyImmutable(int[] anArray) {

    this.myArray = anArray.clone(); // defensive copy

    }

    public String toString() {

    StringBuffer sb = new StringBuffer("Numbers are: ");

    for (int i = 0; i < myArray.length; i++) {

    sb.append(myArray + " ");

    }

    return sb.toString();

    }

}

// the caller cannot change the array after calling the constructor.

int[] array = {1,2};

MyImmutable myImmutableRef = new MyImmutable(array) ;

System.out.println("Before constructing " + myImmutableRef);

array[1] = 5; // change (i.e. mutate) the element

System.out.println("After constructing " + myImmutableRef);

Out put:

Before constructing Numbers are: 1

2

After constructing Numbers are: 1

2




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论