Java design mode Learning 01--Singleton mode (GO)

Source: Internet
Author: User
Tags reflection

Original address: http://blog.csdn.net/xu__cg/article/details/70182988

Java Singleton mode is a common and simpler design pattern. Singleton mode, as the name implies, a class can only have one instance, and provide this one instance to the whole system.
The characteristics of the singleton mode:

    • A singleton class can have only one instance.
    • The Singleton class must create an instance for itself.
    • A singleton class must provide the outside world with a way to obtain an instance.
      Here are a few implementation methods

One, lazy-type single case (can delay loading)

public class SingleTon {     private static SingleTon instance = null ; private SingleTon(){ } public static SingleTon getInstance(){ if(instance==null){ instance=new SingleTon(); } return instance ; }} 

By means of the privatization of the construction method, the class cannot be instantiated outside the environment, only the instance can be obtained through the public method, thus ensuring the instance is unique.
However, the above code is not thread-safe, multi-threaded concurrency, singleton may produce multiple instances, you can use the following methods to improve the GetInstance method to ensure that the lazy single-case thread security.

1. Add synchronization on the getinstance () method

public class SingleTon {     private static SingleTon instance = null ; private SingleTon(){ } //方法同步,调用效率低! public static synchronized SingleTon getInstance(){ if(instance==null){ instance=new SingleTon(); } return instance ; }} 

2. Static internal class type

public class SingleTon {       private static class SingletonClassInstance { private static final SingleTon instance=new SingleTon(); } private SingleTon(){ } //方法没有同步,调用效率高! public static SingleTon getInstance(){ return SingletonClassInstance.instance ; }} 

3. Double check lock type

public class SingleTon {     private volatile static SingleTon instance ;     private SingleTon(){ } public static SingleTon getInstance(){ if(instance==null){ synchronized(SingleTon.class ){ if(instance==null){ instance=new SingleTon(); } } } return instance ; }}

Second, a hungry Man type single case (can not delay loading)

public class SingleTon {     //类初始化时,立即加载这个对象,加载类时,天然的是线程安全的!     private static SingleTon instance=new SingleTon(); private SingleTon(){ } //方法没有同步,调用效率高! public static SingleTon getInstance(){ return instance ; }} 

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

Three, an enumerated singleton

public enum SingleTon {     //这个枚举元素,本身就是单例对象!     INSTANCE;     //添加自己需要的操作!     public void singletonOperation(){ }} 

An enumerated singleton is thread-safe, calls are efficient, and can naturally prevent reflection and deserialization of vulnerabilities.

Iv. prevention of reflection and deserialization

In fact, by using Java reflection or deserialization to get a class instance that is constructed as private, all of the singleton will fail. Therefore, in order to avoid such consequences, appropriate measures need to be taken.

/** * Lazy Singleton mode (how to prevent reflection and deserialization vulnerability) * */PublicClassSingleTonImplementsSerializable {When the class is initialized, the object is not initialized (deferred loading, which is created when it is actually used).Privatestatic SingleTon instance;PrivateSingleTon () {Privatization constructorif (Instance!=null) {throw new runtimeexception (); //Prevent Reflection}} //method synchronization, the call efficiency is low! public static synchronized SingleTon getinstance () {if (instance== null) {Instance=new SingleTon ();} return instance;} //deserialization, if Readresolve () is defined, the object specified by this method is returned directly. You don't need to create new objects alone! private Object readresolve ()  Throws Objectstreamexception {return instance;}}      

Five, how to choose a single example mode implementation

    • Singleton objects consume less resources and do not require delayed loading: enumerations are better than a hungry man
    • The singleton objects occupy a large amount of resources and require delay loading: Static inner class is better than ordinary lazy type

Java design mode Learning 01--Singleton mode (GO)

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.