Home  >  Article  >  Java  >  How to write java singleton pattern

How to write java singleton pattern

(*-*)浩
(*-*)浩Original
2019-05-22 10:53:0810186browse

Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern is a creational pattern, which provides an optimal way to create objects.

How to write java singleton pattern

This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without the need to instantiate an object of the class.

Note:

1. A singleton class can only have one instance. 2. A singleton class must create its own unique instance. 3. The singleton class must provide this instance to all other objects.

java Five ways to write singleton mode:

1. Full-bodied mode (lazy mode)

// 饱汉
// UnThreadSafe
public class Singleton1 {
  private static Singleton1 singleton = null;
  private Singleton1() {
  }
  public static Singleton1 getInstance() {
    if (singleton == null) {
      singleton = new Singleton1();
    }
    return singleton;
  }
}

Advantages: Lazy loading starts quickly, takes up little resources, is instantiated when used, and is lock-free.

Disadvantages: Not thread-safe.

2. Lazy mode (lazy mode) - thread safety

public class Singleton {
    /**
     * 定义一个变量来存储创建好的类实例
     */
    private static Singleton uniqueInstance = null;
    /**
     * 私有化构造方法,好在内部控制创建实例的数目
     */
    private Singleton(){
    }
    /**
     * 定义一个方法来为客户端提供类实例
     * @return 一个Singleton的实例
     */
    public static synchronized Singleton getInstance(){
        //判断存储实例的变量是否有值
        if(uniqueInstance == null){
            //如果没有,就创建一个类实例,并把值赋值给存储类实例的变量
            uniqueInstance = new Singleton();
        }
        //如果有值,那就直接使用
        return uniqueInstance;
    }
    /**
     * 示意方法,单例可以有自己的操作
     */

    public void singletonOperation(){
//功能处理
    }
    /**
     * 示意属性,单例可以有自己的属性
     */
    private String singletonData;
    /**
     * 示意方法,让外部通过这些方法来访问属性的值
     * @return 属性的值
     */
    public String getSingletonData(){
        return singletonData;
    }
}

Advantages: Same as above, but locked.

Disadvantages: synchronized is an exclusive lock and has poor concurrency performance. Even after the creation is successful, obtaining the instance is still a serialized operation.

3. Lazy Mode (Lazy Mode) - Double Check Lock DCL (Double Check Lock)

public class Singleton {
    /**
     * 对保存实例的变量添加volatile的修饰
     */
    private volatile static Singleton instance = null;
    private Singleton(){
    }

    public static Singleton getInstance(){
//先检查实例是否存在,如果不存在才进入下面的同步块
       if(instance == null){
//同步块,线程安全的创建实例
            synchronized(Singleton.class){
//再次检查实例是否存在,如果不存在才真的创建实例
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Advantages: Lazy loading, thread safety.

Note: The instance must be modified with the volatile keyword to ensure complete initialization.

4. Hungry mode

public class Singleton {
//4:定义一个静态变量来存储创建好的类实例
//直接在这里创建类实例,只会创建一次
    private static Singleton instance = new Singleton();
//1:私有化构造方法,好在内部控制创建实例的数目
    private Singleton(){
    }
//2:定义一个方法来为客户端提供类实例
//3:这个方法需要定义成类方法,也就是要加static
//这个方法里面就不需要控制代码了
   public static Singleton getInstance(){
//5:直接使用已经创建好的实例
       return instance;
    }
}

Advantages: Hungry mode is inherently thread-safe and there is no delay when using it.

Disadvantages: Instances are created at startup, slow startup, and possible waste of resources.

5. Holder mode

public class Singleton {
    /**
     * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
     * 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
     */
    private static class SingletonHolder{
        /**
         * 静态初始化器,由JVM来保证线程安全
         */
        private static Singleton instance = new Singleton();
    }
    /**
     * 私有化构造方法
     */
    private Singleton(){
    }
    public static  Singleton getInstance(){
        return SingletonHolder.instance;
    }
}

Advantages: A way to perfectly combine lazy loading and thread safety (no locks). (Recommended)

Related learning recommendations: java basic tutorial

The above is the detailed content of How to write java singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is map in javaNext article:What is map in java