Java enumeration enum and application: enumeration implements Singleton mode

Source: Internet
Author: User
Tags serialization account security

Enumeration as a general language concept, until the birth of Java5 has to say a bit strange, so far many programmers still prefer to use static final form to name constants without using, in general, Java programmers in this way to implement enumerations:

Class enumbyclass{public    static final int red=0;    public static final int green=1;    public static final int blue=2;}

An enumeration implemented in this way is also called an int enumeration pattern, although it is commonly used, but enumerations implemented by int are difficult to guarantee security, meaning that additional maintenance is required when values that are not in the enumeration range are called. In addition, it is not conducive to viewing log and testing.

At this point, we need to start using the Java enumeration type, such as the above int enumeration pattern class if implemented with enum, then the code is as follows:

Enum color{    Red,green,blue;}

The above is a simple use of the enumeration as a constant collection, in fact, enumerating more or using switch, it is also at this time to find the benefits of enumeration in relation to the INT enumeration pattern, which is an example of using an enum to implement switch:

Enum color{    Red,green,blue;} public class Hello {public    static void Main (string[] args) {        Color color=color.red;        int counter=10;        while (counter-->0) {            switch (color) {case                RED:                    System.out.println ("Red");                    Color=color.blue;                    break;                Case Blue:                    System.out.println ("Blue");                    Color=color.green;                    break;                Case Green:                    System.out.println ("green");                    color=color.red;                    Break;}}}}    

If we enumerate patterns in int, it is true that we can use some ++,---like syntactic sugars, but we also need to take into account security issues.

If that's the case, then there's nothing to enumerate about the value of blogging alone.

My personal interest in Enum is primarily due to the fact that I previously had a very experienced enumeration implementation of Singleton when I introduced the code as follows:

Enum singletondemo{    INSTANCE;    public void Othermethods () {        System.out.println ("Something");}    }

Simply a little bit of code to achieve a thread-safe, lazy loading of the single case, rather than the way it is written, it is appropriate to apply the nature of the enum.

When I implemented singleton with enum I introduced three features, free serialization, thread safety, and guaranteed singleton. Here we are going to discuss the question of why.

First of all, we all know that Enum is implemented by class, in other words, Enum can implement many classes of content, including can have member and member function, which is also we can use Enum as a class to achieve the basis of a singleton. In addition, since the enum is implemented by inheriting the Enum class, the enum struct cannot inherit other classes as subclasses, but it can be used to implement interfaces. In addition, the Enum class cannot be inherited, and in the anti-compilation we will find that the class is final.

Secondly, Enum has and only the private constructor, to prevent the external additional structure, which coincides with the singleton pattern, but also to ensure a single case to do a cushion. Here is the private constructor, if we do not go to the handwriting constructor, there will be a default null parameter constructor, we can also give the enumeration variable parameters to implement the initialization of the class. Give an example here.

Enum color{    RED (1), GREEN (2), BLUE (3);    private int code;    Color (int code) {        this.code=code;    }    public int GetCode () {        return code;    }}

It is important to note that the private modifier can be omitted for the constructor, but this does not mean that the constructor's permissions are the default permissions.

At present, we have a preliminary understanding of the structure and characteristics of the enum, then explore the characteristics of the principle level.

To understand how an enum works, you need to decompile it.

When you decompile, you will find that using enumerations is similar to using static class internal loading methods. The enumeration is compiled into the following form:

Public final class T extends enum{

...

}

where Enum is a class that Java provides to the compiler for inheritance. The implementation of the enumerator is actually an uninitialized variable of the public static final T type. If the enumerator has adjoint parameters and the constructor is added manually, it will parse into a static block of code that initializes the variables when the class loads. So, if you use an enumeration to implement a singleton, the load time is actually somewhat similar to the A Hungry man pattern, and does not play a lazy-loading role.

For serialization and deserialization, because each enumeration type and enumeration variable is unique in the JVM, Java has special provisions for serializing and deserializing enumerations, enumerated writeobject, ReadObject, Readobjectnodata, Methods such as Writereplace and Readresolve are disabled by the compiler, and therefore there is no problem of calling ReadObject after implementing the serialization interface to break the singleton.

For thread safety, similar to the normal a hungry man pattern, objects created by static initialization at the first call are thread-safe.

Therefore, the choice of enumeration as the implementation of Singleton, in contrast to other methods, especially the similar a hungry man pattern has the following advantages:

1. Simple code

2. Free serialization

As for Lazy-loading, considering that the general situation does not exist to invoke the Singleton class and does not need to instantiate a singleton case, it is not a big problem even if the lazy-loading is not good. In other words, in addition to enumerating this scheme, the A hungry man pattern is also widely used in single-instance design. For example, Hibernate is the default singleton, and the Hibernateutil class used to get Sessionfactory is established as follows:

public class Hibernateutil {    private static final sessionfactory oursessionfactory;    static {        Try {            configuration configuration = new configuration ();            Configuration.configure ();            Oursessionfactory = Configuration.buildsessionfactory ();        } catch (Throwable ex) {            throw new Exceptionininitializererror (ex);        }    }    public static Session GetSession () throws Hibernateexception {        return oursessionfactory.opensession ();}    }

This is a typical a hungry man pattern, and given that there is only one method for this single case, it is obvious that the pattern itself is optimal and concise. This is because the creation of the sessionfactory is not in the system default way, if you want to use Enum to achieve rather cumbersome and unnecessary. But at least that might require a solution to the problem of free serialization.

Java enumeration enum and application: enumeration implements Singleton mode

Related Article

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.