`
qqdwll
  • 浏览: 131228 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java 中 immutable class 以及怎样实现immutable 类

    博客分类:
  • Java
阅读更多
原文 http://www.javapractices.com/topic/TopicAction.do?Id=29

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.

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.

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
    * 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)
    * 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
    * if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller

In Effective Java, Joshua Bloch makes this compelling recommendation :

"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

It's interesting to note that BigDecimal is technically not immutable, since it's not final.

Example

import java.util.Date;

/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/
public final class Planet {

  public Planet (double aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     //make a private copy of aDateOfDiscovery
     //this is the only way to keep the fDateOfDiscovery
     //field private, and shields this class from any changes that 
     //the caller may make to the original aDateOfDiscovery object
     fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
  }

  /**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */
  public double getMass() {
    return fMass;
  }

  /**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */
  public String getName() {
    return fName;
  }

//  /**
//  * Returns a mutable object - likely bad style.
//  *
//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
//  * since the Date object state can be changed both by this class and its caller.
//  * That is, this class is no longer in complete control of fDate.
//  */
//  public Date getDateOfDiscovery() {
//    return fDateOfDiscovery;
//  }

  /**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */
  public Date getDateOfDiscovery() {
    return new Date(fDateOfDiscovery.getTime());
  }

  // PRIVATE //

  /**
  * Final primitive data is always immutable.
  */
  private final double fMass;

  /**
  * An immutable object field. (String objects never change state.)
  */
  private final String fName;

  /**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */
  private final Date fDateOfDiscovery;
}


分享到:
评论

相关推荐

    hibernate总结

    Java类:材料PO,产品PO,中间PO,中间PO的复合主键类(由于是两个一对多形成的多对多,所以,这里只讲一个一对多,另一个是相同的映射方法) //产品类: public class Product { private Integer cpbh; private ...

    Java的六大问题你都懂了吗

     一、到底要怎么样初始化!  本问题讨论变量的初始化,所以先来看一下Java中有哪些种类的变量。  1. 类的属性,或者叫值域  2. 方法里的局部变量  3. 方法的参数 对于第一种变量,Java虚拟机会自动进行初始...

    javabiginteger源码-Java:Java

    ##-----java.lang.Class类----- 5. 为什么说Class类不能被继承? 6. 为什么说我们不能 new Class()? 7. forName()中执行了什么流程? 8. toString()返回什么? 9. newInstance()中执行了什么? ##-----java.lang....

    Practical Java(中文版(繁体+简体))

    實踐63:審慎㆞定義和實現immutable classes(不可變類) 213 實踐64:欲傳遞或接收mutable objects(可變對象)之object references 時,請實施clone() 215 實踐65:使用繼承(inheritance)或委託(delegation)來...

    Java初学者都必须理解的六大问题

    如果你需要使用equals方法,或者使用任何基于散列码的集合(HashSet,HashMap,HashTable),请察看一下java doc以确认这个类的equals逻辑是如何实现的。    问题三:String到底变了没有?  没有。因为String被...

    sample:核心 Java 示例

    样本 核心 Java 示例 1.Comparable Vs Comparator 2.Equal() & HashCode() 契约 3.Runtime Class 4.Uninstantiable Class 5.Immutable Class

    jomni:Java 8 的对象映射器微型库

    Jomni:Java 8的对象映射器 Jomni 是一个 Java 8 库,它可以很容易地在 Java 中将一种类型的对象转换为另一种类型。 它体积小、可扩展,并且是为 Java 8 用 Ja​​va 8 编写的。 // build the immutable and ...

    Thinking in Java 4th Edition

    Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the ...

    FactoryJill:用于将Java对象设置为测试数据的库

    工厂吉尔 用法 sourceCompatibility = 1.8 dependencies { ...} 特征 支持的: 定义可重复使用的工厂 覆盖字段 关联:将字段定义为其他... class, ImmutableMap . of( " make " , " ford " , " convertible " , false ,

    汪文君高并发编程实战视频资源全集

    │ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高并发编程第二阶段44讲、被动引用和类加载过程的练习巩固训练题.mp4 │ 高并发编程第二阶段45讲、ClassLoader加载阶段发生的...

    汪文君高并发编程实战视频资源下载.txt

    │ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高并发编程第二阶段44讲、被动引用和类加载过程的练习巩固训练题.mp4 │ 高并发编程第二阶段45讲、ClassLoader加载阶段发生的...

    Scala程序设计(第2版)

    19.2 使用动态特征实现Scala 中的动态调用 397 19.3 关于DSL的一些思考 402 19.4 本章回顾与下一章提要 402 第20章 Scala的领域特定语言 403 20.1 DSL 示例:Scala中XML和JSON DSL 404 20.2 内部DSL...

    Scala for the Impatient 2nd (完整英文第二版 带书签)

    13.2 Mutable and Immutable Collections 173 13.3 Sequences 174 13.4 Lists 175 13.5 Sets 177 13.6 Operators for Adding or Removing Elements 178 13.7 Common Methods 180 13.8 Mapping a Function 182 13.9 ...

    Immutables-Android-Example:在Android和GSON上使用Immutables 2.0的示例

    @Value.Immutable public abstract class User { public abstract int id(); public abstract String username(); } 我们可以将其用作: User user = ImmutableUser.builder().id(1).username("olidroide")....

    不可变的:注释处理器,用于创建不可变的对象和构建器。 感觉像番石榴的不可变集合,但对于常规值对象。 包括JSON,Jackson,Gson,JAX-RS集成

    阅读完整的文档,为 // Define abstract value type using interface, abstract class or annotation@Value . Immutablepublic interface ValueObject extends WithValueObject { // extend not-yet-generated ...

    python3.6.5参考手册 chm

    PEP 487: Simpler customization of class creation PEP 487: Descriptor Protocol Enhancements PEP 519: Adding a file system path protocol PEP 495: Local Time Disambiguation PEP 529: Change Windows ...

    hibernate3.6 文档(pdf 格式)

    1.1.2. The first class .......................................................................................... 3 1.1.3. The mapping file ...............................................................

Global site tag (gtag.js) - Google Analytics