The singleton design pattern java

What is a design pattern?

Design patterns are preferred structure of the code, after programming style summary of the theory and a lot of practice, as well as problem-solving way of thinking. Design patterns like classic chess, chess game different, we have different chess, replacing our own re-thinking and exploration.

The so-called singleton pattern , is to adopt a certain way to ensure that the entire software system, for a class there is only an object instance , and the class is only a method to obtain its object instance. If we want class in a virtual machine can only produce an object, we must first class access to the constructor is set to Private . Thus, the object can not be used externally generated new operator class of a class. But inside the class can still produce objects of that class. Since the beginning of the class outside also can not be the object of this class can only be called a static method of the class to return the object class internally created, static methods can only access static member variables in the class, so the class is generated inside the point variables that object must also be defined as static.

Why use a singleton?

a new object needs to take too much time; the need for frequent use of an object;

Russian and Chinese-style singleton pattern: first a new object that someone needs to be used directly;

Single.java

// Russian and Chinese single embodiment 
public  class Single {
     // Constructors privatization 
    Private Single () { 
        
    } 
    // private class variables 
    Private  static Single SINGLE = new new Single ();
     public  static Single the getInstance () {
         return SINGLE; 
    } 
}

Test.java

public class Main {
    
    public static void main(String[] args) {
        Single single = Single.getInstance();
    }
}

Example lazy single mode: the first object is initialized to null, when the object is required to wait until a new, it is only after the object;

Single.java

// Russian and Chinese single embodiment 
public  class Single {
     // Constructors privatization 
    Private Single () { 
        
    } 
    // private class variables 
    Private  static Single instance = null ;
     public  static Single the getInstance () {
         IF (instance == null ) { 
            instance = new new Single (); 
        } 
        return instance; 
    } 
}

Test.java

public class Main {
    
    public static void main(String[] args) {
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        Single s3 = Single.getInstance();
        Single s4 = Single.getInstance();
    }
}

Guess you like

Origin www.cnblogs.com/xiximayou/p/12050037.html