In Java, the singleton pattern is a common design pattern, and the singleton pattern is divided into three kinds: lazy type single case, a hungry man type single case, registration type single case three kinds.
There are a few features of the Singleton model:
1, the Singleton class can have only one instance.
2. The Singleton class must create its own unique instance itself.
3. The Singleton class must provide this instance to all other objects.
A hungry man type Singleton class. At class initialization, you have instantiated the public class Singleton1 { //private default constructor child private Singleton1 () {} //static adornment A unique instance is created when class initializes private static final Singleton1 single = new Singleton1 (); Static Factory method Public static Singleton1 getinstance () { return single; }
Lazy type Singleton class. Instantiate public class Singleton2 { //private default constructor private Singleton2 () {} ///Note at the first call, There is no final private static Singleton2 single=null; Static Factory method public synchronized static Singleton2 getinstance () { if (single = null) {Single = new Sin Gleton2 (); } return single; } }
Import Java.util.hashmap;import java.util.map;//Registered Singleton class is gof in order to overcome the A hungry man type of singleton and lazy single class are not inherited shortcomings and design//similar to spring inside the method, the class name registration, Get it directly from inside next time. public class Regsingleton {private static map<string, regsingleton> Map = new hashmap<string, Regsingleton> ;(); static {Regsingleton single = new Regsingleton (); Map.put (Single.getclass (). GetName (), single); }//Default construction protection protected Regsingleton () {}//static Factory method, return this unique instance public static Regsingleton getinstance (String n AME) {if (name = = null) {name = RegSingleton.class.getName (); } if (Map.get (name) = = null) {try {map.put (name, (Regsingleton) class.forname (name). New Instance ()); } catch (Instantiationexception e) {e.printstacktrace (); } catch (Illegalaccessexception e) {e.printstacktrace (); } catch (ClassNotFoundException e) {e.printstacktrace (); }} return MaP.get (name); The public String is about () {return "Hello, I am Regsingleton."; public static void Main (string[] args) {Regsingleton single = regsingleton.getinstance (null); System.out.println (Single.about ()); System.out.println (Regsingletonchild.getinstance (). About ()); }}
public class Regsingletonchild extends Regsingleton {public regsingletonchild () { } /** * Static Factory method */ static public Regsingletonchild getinstance () { return (regsingletonchild) regsingleton.getinstance ( RegSingletonChild.class.getName ()); } Public String About () { return ' Hello, I am regsingletonchild. '; }}
Java Singleton mode