Singleton mode

zhaozj2021-02-17  57

Key points for Singleton mode:

1. A class can only have one instance

2, you must create this instance yourself

3, this example must be provided to the entire system

Singleton mode implementation method 1

Public static electionleton getinstance () {return m_instance;}}

2, lazy formula singletonpublic class LazySingleton {private static LazySingleton m_instance = null; private LazySingleton () {}; synchronized public static LazySingleton getInstance () {if (m_instance == null) {m_instance = new LazySingleton ();} return m_instance;} }

3, registration of formula singletonimport java.util.HashMap; public class RegSingleton {static private HashMap m_registry = new HashMap (); static {RegSingleton x = new regSingleton ();. M_registry.put (x.getClass () getName (), x );} Protect Regsingleton ()} static public regsingleton getInstance (String name) {if (name == null) {name = "regsingleton";} if (m_registry.get (name) == null) {m_registry.put Name, class.Forname (Name) .newinstance ();} catch (exception e) {system.out.println ("Error Happend.");} return (regsingleton) (m_registry.get (name));}} The comparison of Singleton mode is instantiated when the hungry class is loaded. When the lazy class is loaded, it is not instantiated, and instantiated when the first reference is first referenced.

Hungry Chinese, lazy customs cannot be inherited and the registration can be inherited.

转载请注明原文地址:https://www.9cbs.com/read-30193.html

New Post(0)