Analysis of Android's Singleton Design Pattern

For programmers, a good coding design pattern can greatly improve the performance of software, especially in the Java language, because its memory recovery mechanism is completely different from C++, and it relies on the "garbage collection mechanism" of the JVM. In java, everything is an object. Whenever we create a new object, a certain amount of memory space is allocated in the memory space, so we need as few new objects as possible, so as to reduce the waste of memory space.
The singleton design pattern is to ensure that the class has and only one instance, this pattern is well used in android application development. The singleton design pattern is divided into two types: lazy and hungry. What is the difference between the two?
The lazy style is instantiated whenever it is used, while the hungry style is already instantiated when the class is loaded. From this point of view, the lazy style is more space-saving.
Below we give two ways of writing lazy and hungry:
1. Lazy

/**
 * 单例设计模式之懒汉式
 */
public class LazySingleton {
    private LazySingleton(){}

    private LazySingleton instance = null; //先不建立对象

    //写法一
//  public  LazySingleton getInstance(){
//      if(instance==null){ //先判断是否这空
//          instance = new LazySingleton();  //懒汉式做法
//      }
//      return instance;
//  }

    //写法二 同步加锁防止多线程访问时出错
//  public synchronized  LazySingleton getInstance(){
//      if(instance==null){ //先判断是否这空
//          instance = new LazySingleton();  //懒汉式做法
//      }
//      return instance;
//  }

    //写法三 最安全的方法
    public  LazySingleton getInstance(){
        if(instance==null){ //先判断是否这空
            synchronized (LazySingleton.class){
                instance = new LazySingleton();  //懒汉式做法
            }
        }
        return instance;
    }
}

2. Hungry Chinese

/**
 * 单例设计模式之饿汉式
 */
public class HungrySingleton {

    private HungrySingleton(){}

    private HungrySingleton instance = new HungrySingleton(); //建立对象

    public HungrySingleton getInstance(){
        return instance; //直接返回单例对象
    }

}

Summary:
1. The difference between the so-called "lazy man style" and "hungry man style" is the time when the singleton object is created.
"Lazy type" is to build this singleton object when you really use it.
2. In a single thread, the effect of the two is the same.
3. But in a multi-threaded environment, there is no problem with the hungry type. There may be situations where multiple instances are initialized. In a multi-threaded environment, the wrong place is in the if judgment. Without thread synchronization, the most efficient way to ensure that lazy people do not create multiple objects in a multi-threaded environment is as follows
4. Hungry people are in a hurry, come up Feed directly first.
Lazy people are not in a hurry, feed them whenever they want.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325850749&siteId=291194637