Note 4- head first design pattern singleton

table of Contents

  1, singleton pattern (the Singleton the Pattern)
  2, the concept of
  3, starving the formula: not lazy loading, loading classes directly when initialization
  4, lazy formula: lazy loading, when you first need to use in the examples, it is necessary to consider thread safety
  5 , static inner class
  6, enumeration achieve

 

1、Singleton pattern (the Singleton the Pattern)   <== Back Contents

    To ensure that only one instance of a class, and provide a global access point.

 

2、The concept   <== Back to Contents

The following content Reprinted from blog: 23 kinds of singleton design pattern (https://chenmingyu.top/design-singleton/)

  Singleton: Singleton pattern belongs create schema;

  Definition: to ensure that only one instance of a particular class, and examples of their own and provide the instance of the whole system. Singleton aim is to ensure that the program is running only one instance of a class, and provide a global access point, no matter what the circumstances, will only generate one instance, replacing the cumbersome process of destroying objects created.

  advantage:

1 ) reduces memory costs, avoid the creation of frequent, destroy objects;
 2 ) Avoid multiple assignment of resources;

  Disadvantages:

No interface, not inherited, and the conflict single responsibility principle, a class should only be concerned about the internal logic, not on the outside how to instantiate

 

  How to design a singleton

    How to design the singleton pattern is very simple, only need to consider the question of whether instances can be guaranteed to be globally unique. About instance is guaranteed to be globally unique problem extends:

Are thread-safe, unsafe certainly can not guarantee that only one instance of global 
support serialization, support serialization class, after being serialized anti certainly not a globally unique 
support reflection, certainly not reflective support is globally unique 
if you can is cloned, this can not guarantee the globally unique

 

  So the design of a single case of security issues need to be considered, or many. The common solution to address the problem:

Ensure thread safety, the use of volatile + the synchronized achieve 
prevent serialization attacks, override readResolve method of 
preventing reflection, the commonly used solution is to increase a boolean flag identifies singleton class, in the example of when the first determination flag identifying 
prevent cloning, heavy write clone () method

  

  Implement a simple single case of need to take into account all of the above questions, this time not to write anything useful methods that, the code is already a lot, and that there is no simple way to not only satisfy the above conditions, and the code that is simple, that certainly, the use of single-enumeration cases.

  Singleton pattern to achieve common

Common Singleton pattern implementations probably has five, lazy mode, starving mode, double-checking ways, static inner class, enum achieve

  Sub-classes:

Whether to support lazy loading, lazy mode and into a hungry man model 
thread-safe design to achieve a double-check mode, static inner class implementation 
does not support serialization, reflection, clone, enumerated implementation

  Where lazy mode, starving mode, double-check manner, implementation of static inner classes can be summarized as the following two steps:

  1. constructor privatization, new objects can not be guaranteed outside
  2. The method of obtaining a static current instance (different schemes, to achieve different)

  

  Of course, the easiest way to achieve enumeration, but also the most secure, it is recommended to use an enumeration to achieve, followed by static inner classes are recommended ways.

 

3、Starving formula: not lazy loading, class loading when initialized directly   <== Back Contents

Advantages: thread-safe, simple code.

Disadvantages: not lazy loading, if you can not use this class, it will be instantiated, there is a problem is if this instance rely on external configuration files, parameters or something, before instantiating going to get, otherwise instance exception

/ ** 
 * Singleton: starving formula 
 * @author Oy 
 * 2019 years. 9 @date 3 afternoon 11:13:49 
 * / 
public  class the Singleton { 

    Private  static the Singleton Singleton = new new the Singleton (); 

    Private the Singleton () { 
    } 

    public  static the Singleton the getInstance () {
         return Singleton; 
    } 
}

 

4、Lazy type: lazy loading, when for the first time need to use the example of the need to consider thread safety   <== Back to Contents

  Thread unsafe ways:

/ ** 
 * Singleton: lazy type, thread-safe 
 * @author Oy 
 * 2019 years. 9 @date 3 afternoon 11:15:47 * / 
public  class the Singleton {
     Private  static the Singleton Singleton;
     Private the Singleton () {}
     public  static the Singleton the getInstance () {
         IF ( null == Singleton) { 
            Singleton = new new the Singleton (); 
        } 
        return Singleton; 
    } 
}

  Thread-safe implementation: double check (DCL: Double Check Lock)

/**
 * 单例模式:双重检查(DCL:Double Check Lock)
 * @author oy
 * @date 2019年9月3日 下午11:17:06
 */
public class Singleton {
    private static volatile Singleton singleton;
    private Singleton() {}

    public static Singleton getInstance(){
        if(null == singleton){
            synchronized (Singleton.class){
                if(null == singleton){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

 

  Interview questions: Why modified singleton variables volatile?

1 . Volatile to say, first of all answered in the affirmative volatile visibility
 2 . Prevent reordering optimization, modified if not volatile, multi-threaded, the thread may appear to enter the synchronized code block A, 
execute new Singleton () ;, first to singleton allocate memory, but not yet initialized variable, 
this time thread B enters the getInstance method, the first judge, then singleton has not empty, 
return directly singleton, then certainly an error. Prohibit reordering jvm to optimize the use of volatile after modification, it will not appear on the above issue

 

5、Static inner class   <== Back to Contents

  Use static inner classes also implement lazy loading, use static inner classes to implement a thread-safe, only when the first call to getInstance method will be to load SingletonHolder, initialization SINGLETON

/ ** 
 * Example Single Mode: Static inner class 
 * @author Oy 
 * 2019 years. 9 @date 3 afternoon 11:17:06 
 * / 
public  class the Singleton { 

    Private the Singleton () {} 

    public  static the Singleton the getInstance () {
         return SingletonHolder.SINGLETON; 
    } 

    Private  static  class SingletonHolder {
         Private  static  Final the Singleton SINGLETON = new new the Singleton (); 
    } 
}

 

6、Enumeration achieve   <== Back to Contents

  Enumeration implementation code cleaner, thread-safe and can not be guaranteed enumeration deserialized, reflection and cloning

/ ** 
 * Singleton pattern: enumeration achieve 
 * @author Oy 
 * @date 2019 Nian 9 3 afternoon 11:17:06 
 * / 
public  enum Singleton { 

    SINGLETON; 

    / ** 
     * methods provided 
     * / 
    public  void Method, () { 
        System.out.println ( "enumeration achieved" ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/xy-ouyang/p/11456448.html