Immutable (immutable) mode of Java design mode

Source: Internet
Author: User

Immutable Introduction

immutable objects never change, and the values of their fields are set only once when the constructor is run, and then no longer changed . For example, the two basic data types that are common in the JDK are string and integer, and they are immutable objects. To understand the difference between immutable and mutable, take a look at the following code:


Package Date0804.demo2;import Java.awt.point;public class Immutablestring {public static void main (string[] args) {// string,immutablestring str = new String ("new book"); System.out.println (str); Str.replaceall ("New", "old"); System.out.println (str);//point,mutablepoint point = new Point (0,0); System.out.println (point);p oint.setlocation (1, 0); System.out.println (point);}}



Run the result as



New BookNew bookjava.awt.point[x=0,y=0]java.awt.point[x=1,y=0]



We see that the value of point has changed, and the value of STR has not changed. Once an object of type string is created in memory, its value will not change, only a pointer to that object reference. If you want to create a string that can be changed, you can use the StringBuilder and StringBuffer classes to create strings that are more flexible and allow you to add, insert, and append new content.


[Expand, the following piece of code is not related to immutable] look at another interesting string instance:


Package Date0804.demo2;public class Immutablestring {public static void main (string[] args) {string str=new string ("xyz") ; Change (str); System.out.println (str);} public static void Change (String s) {s= "XML";}}



The output of the above code is:



Xyz



As I understand it, the parameters of a method in Java are passed by value, where Java creates a string "xyz" on the memory heap and assigns the memory address of the string to the STR variable, which is a reference to the "XYZ" memory address stored in STR, and the Change () method is passed by value , which is equivalent to creating another string object "XML", and this object has another different address reference, not the previous x-stored reference.


In concurrent programming, a universally accepted principle is to use immutable objects as much as possible to create simple, reliable code. immutable objects are particularly useful because they cannot be modified after they are created, so there is no error due to thread interference or memory consistency errors. the use of immutable objects reduces the overhead of garbage collection and also reduces the extra code used to ensure that there are no concurrency errors with mutable objects.

Advantages of immutable

Immutable objects can simplify our program code to a great extent, and have the following advantages:

--immutable objects are easy to construct, use and test;

--Automatic thread-safe type, avoid some complicated synchronization problems;

--No need for a copy constructor (copy constructor);

--no need for a clone implementation;

--Allows the lazy mode of the hashcode () method to be implemented and caches its return value;

--When you are a field, you do not need to copy;

--once constructed, it has type invariance and does not have to be inspected;

--[Quotes]If an immutable object throws an exception, it's never left in an undesirable or indeterm Inate state.

the design method of immutable

--Ensure that the class is not overwritten, that the class is not inherited, and that this is achieved with the modifier final, or by using the static factory creation method to ensure that the constructor is private;

--all fields must be private, plus the modifier final;

--all settings need only a simple constructor, do not use empty constructors, do not use JavaBean-style constructors;

--do not provide any way to change the object, not only the setter, all the methods to modify the state of the object should be avoided;

--If the class has objects with mutable fields, it must be conservative and can only be modified by the class itself.

Code instance of the immutable class
Final public class Immutablergb {//constant field final private int red;    Final private int green;    Final private int blue;    Final private String name;                       Private method, check if the value of the three primaries is between 0~255, and if not, throw an exception private void check (int red, int green, int blue) {if (Red < 0 | | Red > 255 | | Green < 0 | | Green > 255 | | Blue < 0 | |        Blue > 255) {throw new illegalargumentexception ();                        }}//A unique construction method, first check that the field is legal, and then pass all fields public Immutablergb (int red, int green,        int blue, String name) {Check (red, green, blue);        this.red = red;        This.green = green;        This.blue = blue;    THIS.name = name; }//get method public int getRGB () {return (Red << 16) | (Green << 8) |    Blue);    }//get method Public String GetName () {return name; }//Invert the color value public Immutablergb INvert () {return new Immutablergb (255-red, 255-green, 255-blue,    "Inverse of" + name); }}

As you can see from the previous section of the code, this is an immutable class whose object is an immutable object. Once an object is created, it is not modified. The last piece of code reflects the fact that once the object has been modified, do not return the object itself, but rather copy the return. This immutable object solves the competition problem in concurrent programming well, regardless of thread synchronization, because once the object is created, it does not change.


incorrect use of the immutable class

The following code shows that the surface looks like a immutable class, which is actually a mutable class:


Import Java.util.date;public Final class Brokenperson{private string firstname;private string lastname;private Date dob; Public Brokenperson (String firstName,  string lastName, Date dob) {this.firstname = Firstname;this.lastname = Lastname;this.dob = DOB;} Public String Getfirstname () {return this.firstname;} Public String Getlastname () {return this.lastname;} Public Date Getdob () {return this.dob;}}



This code looks fine, butNote that DOB is a Date object, which means that it is a mutable object field,If the customer uses the following code to call:



Date mydate = new Date (); Brokenperson MyPerson =  new Brokenperson ("David", "O ' Meara", mydate); System.out.println (Myperson.getdob ()); Mydate.setmonth (Mydate.getmonth () + 1); System.out.println (Myperson.getdob ());



Then, the result of the return could be



Mon Mar 21:34:16 gmt+08:00 2013Thu Apr 21:34:16 gmt+08:00 2013



So, we see that MyPerson is actually a mutable object, and the problem is that Brokenperson has a field with a Mutable object, soInstead of directly referencing it, we should use its copy to create the object:


Import Java.util.date;public Final class Betterperson{private string firstname;private string lastname;private Date dob; Public Betterperson (String firstName,  string lastName, Date dob) {this.firstname = Firstname;this.lastname = Lastname;this.dob = new Date (Dob.gettime ());}                 //.......                Public date Getdob ()       {return new date (This.dob.getTime ());        

Note that for all mutable fields, you should use a copy to "Go in and out" of the class in order to be more secure.

Summarize

This paper briefly introduces the advantages of immutable and its design methods, the biggest disadvantage of immutable objects is the overhead of creating objects, because each operation will produce a new object , but reasonable use of immutable can bring great benefits. Immutable classes are best suited for values that represent abstract data types, such as numbers, enumeration types, or colors. Wrapper classes for the basic data types in the Java class library (such as Integer, Long, and Float) are immutable, and other numeric types, such as BigInteger and BigDecimal, are immutable. A class that represents a rational number of complex or arbitrary precision will be more appropriate to design as an immutable class. Even abstract types that contain many discrete values, such as vectors or matrices, are also good for designing immutable classes, depending on your application.
Another good example of a suitable implementation with an immutable class is an event. Events have a shorter lifespan and are often consumed in threads other than the thread that created them, so making them immutable is more of a benefit than a disadvantage. Most AWT event classes are not strictly implemented as immutable classes. Similarly, it is advisable to have message objects designed to be immutable among the components of a communication system.







Immutable (immutable) mode of Java design mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.