Singleton single-State Design Mode singleton
1. Concept
1. In Java applications, only one instance of a Class can exist. |
2. One instance |
1) private constructor 2) Private Static instances 3) Public and static access |
1) prevent creating new instances 2) Prevent Modification 3) must be able to obtain |
Public class Singleton {// 1. private constructor private Singleton () {}// 2. private static instance variable private static Singleton sl = new Singleton (); // 3. public static access method public static Singleton getsingleton () {return sl ;}}
1. Cool and lazy
1. Evil guys |
Create an object from the beginning |
1) create an object in advance |
2. Lazy |
Create an object as needed |
1) create an object only when using the method |
3. Attackers |
4. Lazy |
Public class badmash {// 1. private constructor private badmash () {}// 2. private static instance variable private static badmash bmBadmash = new badmash (); // 3. public static access method public static badmash getBadmash () {return bmBadmash ;}} |
Public class sluggard {// 1. private constructor private sluggard () {}// 2. private static variable instance private static sluggard sg = null; // 3. public static access method public static sluggard getSluggard () {if (sg = null) {sg = new sluggard () ;}return sg ;}} |
1) attackers are thread-safe. |
1) The Lazy thread is insecure. |
1. Thread Security
1) The role of thread synchronization: control the code and queue the thread for execution,
Synchronization keyword |
Synchronous Code Block |
Public class sluggard_synchro { // 1. Private Constructor Private sluggard_synchro (){ } // 2. Private static variable instance Private static sluggard_synchro sg = null; // 3. Public static access method Public static synchronized sluggard_synchro getSluggard (){ If (sg = null ){ Sg = new sluggard_synchro (); } Return sg; } } |
Public class sluggard_code { // 1. Private Constructor Private sluggard_code (){ } // 2. Private static variable instance Private static sluggard_code sg = null; // 3. Public static access method Final private static Object OBJECT = new Object (); Public static sluggard_code getSluggard (){ Synchronized (OBJECT ){ If (sg = null ){ Sg = new sluggard_code (); } } Return sg; } } |
Low Efficiency |
4. Double Lock
Public class sluggard_bilayer { // 1. Private Constructor Private sluggard_bilayer (){ } // 2. Private static variable instance Private static sluggard_bilayer sg = null; // 3. Public static access method Final private static Object OBJECT = new Object (); Public static sluggard_bilayer getSluggard (){ If (sg = null) {// condition 1 Synchronized (OBJECT ){ If (sg = null) {// condition 2 Sg = new sluggard_bilayer (); } } } Return sg; } } |
Note: Services at the Android system level are generally designed as one instance, that is, a single instance.