Home >Java >javaTutorial >Detailed explanation of examples of Java singleton pattern

Detailed explanation of examples of Java singleton pattern

黄舟
黄舟Original
2017-10-16 10:34:261182browse

This article mainly introduces the relevant information of detailed examples of java singleton mode. I hope that this article can help everyone thoroughly understand and master this part of the content. Friends in need can refer to

java singleton Detailed explanation of examples of example pattern

Concept:

The singleton pattern in java is a common design pattern. There are three types of singleton patterns. : There are three types: lazy man-style singleton, hungry man-style singleton, and registration-style singleton. ​

The singleton mode has the following characteristics:

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

The singleton pattern ensures that a class has only one instance, instantiates itself and provides this instance to the entire system. In computer systems, thread pools, caches, log objects, dialog boxes, printers, and graphics card driver objects are often designed as singletons. These applications all have more or less the functionality of resource managers. Each computer can have several printers, but there can only be one Printer Spooler to prevent two print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent one communication port from being called by two requests at the same time. In short, the purpose of choosing the singleton mode is to avoid inconsistent states and avoid long-term policies.

First look at a classic singleton implementation.


public class Singleton {
  private static Singleton uniqueInstance = null;

  private Singleton() {
    // Exists only to defeat instantiation.
  }

  public static Singleton getInstance() {
    if (uniqueInstance == null) {
      uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
  // Other methods...
}

Singleton avoids the class from being instantiated externally by limiting the constructor to private. Within the scope of the same virtual machine, the only instance of Singleton can only pass getInstance( ) method access. (In fact, it is possible to instantiate a class with a private constructor through the Java reflection mechanism, which will basically invalidate all Java singleton implementations. This issue will not be discussed here. Let’s pretend that the reflection mechanism does not exist. .)

But the above implementation does not consider thread safety issues. The so-called thread safety means: if there are multiple threads running at the same time in the process where your code is located, these threads may run this code at the same time. If the results of each run are the same as those of single-threaded runs, and the values ​​of other variables are the same as expected, it is thread-safe. In other words: the interface provided by a class or program is an atomic operation for threads or switching between multiple threads will not cause ambiguity in the execution results of the interface, which means that we do not need to consider synchronization issues. Obviously the above implementation does not meet the requirements of thread safety, and multiple Singleton instances are likely to appear in a concurrent environment.


public class TestStream {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  } 
  //该类只能有一个实例
  private TestStream(){}  //私有无参构造方法
  //该类必须自行创建
  //有2种方式
  /*private static final TestStream ts=new TestStream();*/
  private static TestStream ts1=null;
  //这个类必须自动向整个系统提供这个实例对象
  public static TestStream getTest(){
    if(ts1==null){
      ts1=new TestStream();
    }
    return ts1;
  }
  public void getInfo(){
    System.out.println("output message "+name);
  }
}
/**
 * 
 */
public class TestMain {
  public static void main(String [] args){
    TestStream s=TestStream.getTest();
    s.setName("张孝祥");
    System.out.println(s.getName());
    TestStream s1=TestStream.getTest();
    s1.setName("张孝祥");
    System.out.println(s1.getName());
    s.getInfo();
    s1.getInfo();
    if(s==s1){
      System.out.println("创建的是同一个实例");
    }else if(s!=s1){
      System.out.println("创建的不是同一个实例");
    }else{
      System.out.println("application error");
    }
  }
}

Run result:


张孝祥
张孝祥
output message 张孝祥
output message 张孝祥
创建的是同一个实例

Conclusion: From the result, we can know the singleton The pattern provides an object-oriented application with a unique access point to objects. No matter what function it implements, the entire application will share an instance object.

1. Hungry Chinese style singleton class


//饿汉式单例类.在类初始化时,已经自行实例化 
public class Singleton1 {
  //私有的默认构造子
  private Singleton1() {}
  //已经自行实例化 
  private static final Singleton1 single = new Singleton1();
  //静态工厂方法 
  public static Singleton1 getInstance() {
    return single;
  }
}

2. Lazy Chinese style singleton class


//懒汉式单例类.在第一次调用的时候实例化 
public class Singleton2 {
  //私有的默认构造子
  private Singleton2() {}
  //注意,这里没有final  
  private static Singleton2 single=null;
  //静态工厂方法 
  public synchronized static Singleton2 getInstance() {
     if (single == null) { 
       single = new Singleton2();
     } 
    return single;
  }
}

3. Registration singleton class


import java.util.HashMap;
import java.util.Map;
//登记式单例类.
//类似Spring里面的方法,将类名注册,下次从里面直接获取。
public class Singleton3 {
  private static Map<String,Singleton3> map = new HashMap<String,Singleton3>();
  static{
    Singleton3 single = new Singleton3();
    map.put(single.getClass().getName(), single);
  }
  //保护的默认构造子
  protected Singleton3(){}
  //静态工厂方法,返还此类惟一的实例
  public static Singleton3 getInstance(String name) {
    if(name == null) {
      name = Singleton3.class.getName();
      System.out.println("name == null"+"--->name="+name);
    }
    if(map.get(name) == null) {
      try {
        map.put(name, (Singleton3) Class.forName(name).newInstance());
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
    return map.get(name);
  }
  //一个示意性的商业方法
  public String about() {  
    return "Hello, I am RegSingleton.";  
  }  
  public static void main(String[] args) {
    Singleton3 single3 = Singleton3.getInstance(null);
    System.out.println(single3.about());
  }
}

The above is the detailed content of Detailed explanation of examples of 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