This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Singleton Pattern:

Ensure that a class has only one object. The constructor of a singleton class is private, preventing the outside world from using the constructor to create arbitrarily many instances directly. Because the constructor is private, the singleton class cannot be inherited.

Features:

A singleton class can have only one instance.

2>, the singleton class must create its own unique instance.

The singleton class must provide this instance to all other objects.

Singleton mode is divided into three types: lazy singleton, hungry singleton and registered singleton.

1. Hangry singleton

Package singleton pattern; When the class is loaded, the static variable instance is initialized, the private constructor of the class is called, and a unique instance of the singleton class is created. * @author xcbeyond * @date 2012-5-1 am 11:56:26 */ Public class EagerSingleton {private static final EagerSingleton instance = new EagerSingleton(); Private EagerSingleton() {} public static EagerSingleton getInstance() {return instance; }}Copy the code

Lazy singleton

Unlike hunchback singletons, lazy singletons instantiate themselves the first time they are referenced. If the loader is static, the lazy singleton class will not instantiate itself when it is loaded.

Package singleton pattern; /** * public class LazySingleton {private static LazySingleton {private static LazySingleton instance = null; Private LazySingleton(){} Synchronized public static LazySingleton getInstance () {if(instance == null) {instance = new synchronized public static LazySingleton getInstance () {if(instance == null) {instance = new LazySingleton(); } return instance; }}Copy the code

3. Registered singleton

In order to overcome the uninheritable disadvantage of hungry singleton class and lazy singleton class, registration singleton class is introduced.

Package singleton pattern; import java.util.HashMap; /** * Register singleton classes: overcomes the uninheritable disadvantage of hungry and lazy singleton classes. * @author xcbeyond * @date 2012-5-1 PM 12:35:23 */ public class RegisterSingleton {private static HashMap reg = new HashMap(); static { RegisterSingleton x = new RegisterSingleton(); reg.put(x.getClass().getName(), x); } // protected RegisterSingleton () {// Static factory method, Static RegisterSingleton getInstance(String name) {if(name == null) {name = "RegisterSingleton"; } if(reg.get(name)==null) { try{ reg.put(name, Class.forName(name).newInstance()); }catch(Exception e) { System.out.println("Error happened"); } } return (RegisterSingleton)reg.get(name); }}Copy the code