Singleton mode
1
- 1
- 2
-
Listing 3
Definition: A class produces only one instance in the system
Advantages: For frequently used objects, new time can be omitted, which is an objective system performance improvement for heavyweight objects.Lower memory usage, less GC times and shorter GC pause time
//Singleton objects must be created when the hungry Chinese class is first used public class Singleton { public static int STATUS=1; private Singleton(){ System.out.println("Singleton is create"); } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } } //In the lazy concurrent environment, the performance of locks is poor when the competition is fierce. public class LazySingleton { private LazySingleton() { System.out.println("LazySingleton is create"); } private static LazySingleton instance = null; public static synchronized LazySingleton getInstance() { if (instance == null) instance = new LazySingleton(); return instance; } } //Static internal classes // sets the two advantages mentioned above public class StaticSingleton { public static int STATUS; private StaticSingleton(){ System.out.println("StaticSingleton is create"); } private static class SingletonHolder { private static StaticSingleton instance = new StaticSingleton(); } public static StaticSingleton getInstance() { return SingletonHolder.instance; } }
Be careful: In addition, there is a double checking mode to create singletons, which is ugly and complex, even in the low version can not guarantee correctness, and is not recommended for use.
Invariant pattern
Definition: Once an object is created, its internal state never changes, so it is always thread-safe Use scenarios: After object creation, internal state and data no longer change Objects need to be shared and frequently accessed by multiple threads
public final class PCData { //The parent class remains unchanged, and the child class must remain unchanged, but this cannot be guaranteed, so use final. private final int intData; //Be assigned only once public PCData(int d){ intData=d; } public PCData(String d){ intData=Integer.valueOf(d); } public int getData(){ return intData; } @Override public String toString(){ return "data:"+intData; } }
Be careful: String classes are also invariant, guaranteeing performance under multithreading