不可变类:一旦创建,状态无法改变
关于创建不可变类有很多规则,下面一一介绍这些规则:
目录
定义不可变的益处
如何让类不可变
在Java文档中,有关于如何定义不可变类指南: click here
来点优雅的,定义一个private的构造方法,通过 工厂方法构造对象
只说太抽象,还是来点实例痛快
import java.util.Date;
/**
* Always remember that your instance variables will be either mutable or immutable.
* Identify them and return new objects with copied content for all mutable objects.
* Immutable variables can be returned safely without extra effort.
* */
public final class ImmutableClass
{
/**
* Integer class is immutable as it does not provide any setter to change its content
* */
private final Integer immutableField1;
/**
* String class is immutable as it also does not provide setter to change its content
* */
private final String immutableField2;
/**
* Date class is mutable as it provide setters to change various date/time parts
* */
private final Date mutableField;
//Default private constructor will ensure no unplanned construction of class
private ImmutableClass(Integer fld1, String fld2, Date date)
{
this.immutableField1 = fld1;
this.immutableField2 = fld2;
this.mutableField = new Date(date.getTime());
}
//Factory method to store object creation logic in single place
public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
{
return new ImmutableClass(fld1, fld2, date);
}
//Provide no setter methods
/**
* Integer class is immutable so we can return the instance variable as it is
* */
public Integer getImmutableField1() {
return immutableField1;
}
/**
* String class is also immutable so we can return the instance variable as it is
* */
public String getImmutableField2() {
return immutableField2;
}
/**
* Date class is mutable so we need a little care here.
* We should not return the reference of original instance variable.
* Instead a new Date object, with content copied to it, should be returned.
* */
public Date getMutableField() {
return new Date(mutableField.getTime());
}
@Override
public String toString() {
return immutableField1 +" - "+ immutableField2 +" - "+ mutableField;
}
}
验证以上不可变类:
import java.util.Date;
public class MainTest
{
public static void main(String[] args)
{
ImmutableClass im = ImmutableClass.createNewInstance(100,"test", new Date());
System.out.println(im);
tryModification(im.getImmutableField1(),im.getImmutableField2(),im.getMutableField());
System.out.println(im);
}
private static void tryModification(Integer immutableField1, String immutableField2, Date mutableField)
{
immutableField1 = 10000;
immutableField2 = "test changed";
mutableField.setDate(10);
}
}
输出结果如下:
100 - test - Tue Jun 09 23:14:01 CST 2015
100 - test - Tue Jun 09 23:14:01 CST 2015
从输出中可以看出:即使通过对象引用改变对象变量,值依然不改变,因此类是不可变类
参考这里:click here
涉及资料:click here
官方教程: click here
原文地址:http://blog.csdn.net/topwqp/article/details/46433283