Source: software secrets-Design Patterns
Singleton Pattern)
Definition: make sure that a class has only one instance, and provide the method for obtaining this instance to the entire system.
Highlights of Singleton mode:
1. Each type can only have one instance.
2. This class must create its own instance.
3. This class must provide this instance to the system.
Schema structure:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel + 31qO7z9 + kernel/zPC9wPgo8cD48L3A + CjxwcmUgY2xhc3M9 "brush: java;"> // Singleton mode ------- thread security package com. singleton; public class Singleton {// class shared Instance Object private static Singleton singleton = null; // private constructor private Singleton () {System. out. println ("This is Singleton! ");} // Synchronized ensures thread security and avoids competition from public synchronized static Singleton getInstance () {// checks whether the shared object is null, if yes, a new if (singleton = null) {singleton = new Singleton ();} return singleton ;}}
Package com; import com. singleton. singleton; // test program public class Client {public static void main (String [] args) {// obtain Singleton singleton = Singleton for a single instance. getInstance (); Singleton singleton2 = Singleton. getInstance (); if (singleton = singleton2) {System. out. println ("this is the same object");} else {System. out. println ("this is not the same object ");}}}
Ii. Global object instance as a singleton object
// Create a global object instance of the class as the singleton object package com. singleton; public class Singleton1 {// class shared Instance Object Instantiation private static Singleton1 singleton = new Singleton1 (); private Singleton1 () {System. out. println ("This is Singleton1! ");} Public static Singleton1 getInstance () {return singleton ;}}
Package com; import com. singleton. singleton1; public class Client1 {public static void main (String [] args) {// obtain Singleton1 singleton = Singleton1.getInstance (); Singleton1 singleton2 = Singleton1.getInstance (); if (singleton = singleton2) {System. out. println ("this is the same object");} else {System. out. println ("this is not the same object ");}}}