Design mode 3: single case mode

1, Overview of design patterns

1.1 introduction to design mode

  1. Design pattern is the useful experience that programmers have summed up in the face of similar software engineering design problems. Pattern is not code, but the general knowledge of a certain kind of problems
    With solutions, design patterns represent best practices. These solutions have been developed by many software developers for a long time
    After a period of trial and error.

  2. The essence of design pattern improves the maintainability, universality and expansibility of software, and reduces the complexity of software

  3. < < Design Patterns > > is a classic book written by Erich Gamma, Richard Helm, Ralph Johnson and John vlisides design (commonly known as the "GOF of the four")

  4. Design patterns are not limited to a certain language. java, php and c + + all have design patterns

1.2 type of design mode

  • Design patterns are divided into three types, a total of 23
  1. Creation mode: Singleton mode, abstract factory mode, prototype mode, builder mode and factory mode
  2. Structural mode: adapter mode, bridge mode, decoration mode, combination mode, appearance mode, Hengyuan mode and agent mode.
  3. Behavioral model:
  4. Version method mode, command mode, visitor mode, iterator mode, observer mode, mediator mode, memo mode
    Interpreter mode (interpreter mode), status mode, policy mode, responsibility chain mode (responsibility chain mode)

2, Single case design mode

2.1 introduction to single case design mode

The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system,
And this class only provides a method (static method) to get its object instance.

For example, Hibernate's SessionFactory acts as a proxy for the data storage source and is responsible for creating the Session object. SessionFactory is not
Lightweight. Generally, only one SessionFactory is required for a project, which will use the singleton mode.

2.2 eight methods of single case design mode

There are eight methods for singleton mode:

  1. Hungry Han formula (static constant)
  2. Hungry Chinese style (static code block)
  3. Lazy (thread unsafe)
  4. Lazy (thread safety, synchronization method)
  5. Lazy (thread safe, synchronous code block)
  6. duplication check
  7. Static inner class
  8. enumeration

2.3 hungry Han formula (static constant)

  • The steps are as follows
    • Constructor Privatization (prevent new)
    • Class
    • Expose a static public method: getInstance
  • code implementation
//Hungry Han formula (static constant)
class Singleton{
    //Privatization constructor
    private Singleton(){

    }

    //static const 
    private static Singleton instance =  new Singleton();

    //Write a public static method to return the instance object
    public Singleton getInstance(){
        return instance;
    }


}
  • Description of advantages and disadvantages
    • Advantages: the writing method is simple, and the instantiation is completed when the class is loaded. Thread synchronization problems are avoided
    • Disadvantages: instantiation is completed when the class is loaded. If this object is not used from beginning to end, it will cause a waste of memory
    • Conclusion: it may cause memory waste

2.4 hungry Chinese style (static code block)

//Hungry Han style
class Singleton{
    //Privatization constructor
    private Singleton(){

    }

    //static const 
    private static Singleton instance ;

    static {//Creating objects in static code blocks
        instance = new Singleton();
    }

    //Write a public static method to return the instance object
    public Singleton getInstance(){
        return instance;
    }


}

  • The advantages and disadvantages are the same as above

2.5 lazy style

//Lazy style
class Singleton{
    //Privatization constructor
    private Singleton(){

    }

    //static const 
    private static Singleton instance ;


    //Create objects when they are needed
    public Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }


}
  • Advantages and disadvantages
    • It has the effect of Lazy Loading, but it can only be used under single thread
    • In multithreading, multiple instances may be generated
    • Conclusion: do not use this method in actual development

2.6 lazy (thread safety, synchronization method)

// Lazy (thread safety, synchronization method)
class Singleton {
private static Singleton instance;
private Singleton() {}
//Provide a static public method, add synchronous processing code, and solve thread safety problems
//Lazy style
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
  • Advantages and disadvantages
    • Solves the thread safety problem
    • Low efficiency
    • Conclusion: not recommended

2.7 lazy (thread safe, synchronous code block)

  • Not recommended

2.8 double check

//Lazy (double judgment)
class Singleton{
    //Privatization constructor
    private Singleton(){

    }

    //static const 
    private static Singleton instance ;


    //Create objects when they are needed
    public Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }

        }
        return instance;
    }


}
  • Advantages and disadvantages
    • The concept of double check is often used in multithreading development to ensure thread safety
    • Thread safety; Delayed loading; High efficiency
    • Conclusion: it is recommended to use

2.9 static internal class

// The static internal class is completed, which is recommended
class Singleton {
private static volatile Singleton instance;
//Constructor privatization
private Singleton() {}
//Write a static inner class with a static attribute Singleton
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
//Provide a static public method and directly return singletoninstance INSTANCE
public static synchronized Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
  • Advantages and disadvantages:
    • This method adopts the mechanism of class loading to ensure that there is only one thread when initializing the instance.
    • The static internal class method will not be instantiated immediately when the Singleton class is loaded, but only when the getInstance method is called when instantiation is needed
      The SingletonInstance class will be loaded to complete the instantiation of Singleton.
    • The static properties of the class will only be initialized when the class is loaded for the first time, so here, the JVM helps us ensure the safety of threads
      During initialization, other threads cannot enter.
    • Advantages: thread insecurity is avoided, delayed loading is realized by using the characteristics of static internal classes, and the efficiency is high
    • Conclusion: it is recommended to use

2.10 enumeration

//Using enumeration, you can realize singleton, which is recommended
enum Singleton {
    INSTANCE; //attribute
public void sayOK() {
System.out.println("ok~");
}
}
  • Advantages and disadvantages
    • With jdk1 5 to implement the singleton mode. It can not only avoid the problem of multi-threaded synchronization, but also prevent deserialization and re creation
      New object
    • This approach is advocated by Josh Bloch, author of Effective Java
    • Conclusion: it is recommended to use

2.11 source code analysis of single case mode in JDK application

In our JDK, Java Lang. runtime is the classic singleton mode (hungry Chinese style)

2.12 notes and details of singleton mode

  • The singleton mode ensures that there is only one object of this class in the system memory, which saves system resources. For some objects that need to be created and destroyed frequently, it makes
    Using singleton mode can improve system performance
  • When you want to instantiate a singleton class, you must remember to use the corresponding method to get the object instead of new
  • Scenarios in which singleton mode is used: objects that need to be created and destroyed frequently, objects that take too much time or resources to create (i.e. heavyweight)
    Object), but frequently used objects, tool objects, and objects that frequently access databases or files (such as data sources, session factories, etc.)

Keywords: Java Singleton pattern

Added by darktimesrpg on Sat, 26 Feb 2022 04:22:32 +0200