03 On the [type] create a singleton to understand and use

Singleton

Vernacular: the so-called single-case model, this class is in your system, just as there is one, is to prevent the creation of duplicate objects, destroy objects brought memory overhead. And provide a global point of access in this category among

Mainly to solve: a global classes used to create and destroy frequently.

When to use: when you want to control the number of instances, to save system resources.

 

Soul artist, or starting a drawing of the way, illustrate this idea, image understanding, I think this is the best knowledge and understanding of the way

We all know, Windows system has a global task manager , use the keyboard shortcut Ctrl + Shift + Esc can call up the Task Manager,

Task Manager after the system starts, there will be only one user when using the shortcut key is to call the system a global point of access , through this access point, the system return Task Manager to our users,

This is the most basic example of a single-mode features: global only one, to provide global access point is used to call a single case, as well as the constructor private (only be created by the system itself)

 

As another chestnut:

We all know that we SpringBoot as a server, the front desk returns the data, the general returns are JsonObject

The Object All controllers can be used to return data, we can consider here the Singleton pattern to initialize the class,

Singleton here divided into several modules;

  • Lazy style
  • Hungry man type (most common) initialization class member variable is initialized when he
class public JSONObject { 

    Private static the Map <String, Object> = new new Map the HashMap <> (16 ); 

    // private constructor 
    Private JSONObject () {} 

    // provide global access point synchronized (thread-safe) 
    public static the synchronized Object resultOk ( Data Object) {  map.clear (); 
 map.put ( "Status", "OK" );  map.put ( "Data" , Data); map.put ( "MSG", "request was successful" ); return Map ;} // provide global access point the synchronized static public Object resultError (String MSG) {map.clear (); map.put ( "Status", "OK" ); map.put ( "Data", null ); Map. PUT ( "MSG" , MSG); return Map;} }

 

We tried this call

    static void public main (String [] args) { 
        System.out.println (JsonObject.resultError ( "password is not blank" )); 
        System.out.println (JsonObject.resultOk ( "192.168.0.1" )); 
    }

 

 

This completes a single-mode embodiment of a starving formula (common) of

Guess you like

Origin www.cnblogs.com/ChromeT/p/11774114.html