Home > Java > javaTutorial > A brief introduction to the singleton pattern in Java

A brief introduction to the singleton pattern in Java

黄舟
Release: 2017-10-12 10:17:13
Original
1357 people have browsed it

This article mainly introduces the simple related information of Java singleton mode in detail, which has certain reference value. Interested friends can refer to it

1. Concept

The singleton pattern is a commonly used software design pattern. It contains only one special class called a singleton class in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution. In my opinion, a singleton does not allow the outside world to create objects.

1.1 Concept Analysis

For singletons, from the above conceptual analysis, the following conditions should be met:

First: There can only be A singleton object;

Second: The singleton class must create its own unique instance object;

Third: This instance object can be accessed by the outside world, and the outside world cannot create it by itself object.

2. Several common methods of singleton mode

In Java, the singleton mode is generally divided into lazy man style and hungry man style. Type, and registration type, but registration type is generally less seen, so it is easy to ignore. If the author hadn't suddenly wanted to summarize it today and searched for information on the Internet, I wouldn't have noticed this. The code is posted in this way and explained below.

2.1 Hungry-style singleton class


package com.ygh.singleton;
/**
 * 饿汉式单例类
 * @author 夜孤寒
 * @version 1.1.1
 */
public class HungerSingleton {
  //将构造方法私有,外界类不能使用构造方法new对象
  private HungerSingleton(){}
  //创建一个对象
  private static final HungerSingleton lazySinleton=new HungerSingleton();
  //设置实例获取方法,返回实例给调用者
  public static HungerSingleton getInstance(){
    return lazySinleton;
  }
}
Copy after login

Write a test class to test whether the singleton is implemented:


package com.ygh.singleton;
/**
 * 测试单例类
 * 
 * @author 夜孤寒
 * @version 1.1.1
 */
public class Test {
  public static void main(String[] args) {
    /*
     * 构造方法私有化,不能够使用下面方式new对象
     */
    //HungerSingleton hungerSingleton=new HungerSingleton();
    //使用实例获取方法来获取对象
    HungerSingleton h1=HungerSingleton.getInstance();
    HungerSingleton h2=HungerSingleton.getInstance();
    System.out.println(h1==h2);//true
  }
}
Copy after login

As can be seen from the above: the two references of this test class are equal, which means that the two references point to the same object, and this also coincides with the singleton mode standard. Here, the hungry Chinese introduction ends.

2.2 Hungry-style singleton class


package com.ygh.singleton;
/**
 * 懒汉式单例类
 * @author 夜孤寒
 * @version 1.1.1
 */
public class LazySingleton {
  //将构造方法私有,外界类不能使用构造方法new对象
  private LazySingleton(){}
  //创建一个对象,不为final
  private static LazySingleton lazySingleton=null;
  //设置实例获取方法,返回实例给调用者
  public static LazySingleton getInstance(){
    //当单例对象不存在,创建
    if(lazySingleton==null){
      lazySingleton=new LazySingleton();
    }
    //返回
    return lazySingleton;
  }
}
Copy after login

Test class:


package com.ygh.singleton;
/**
 * 测试单例类
 * 
 * @author 夜孤寒
 * @version 1.1.1
 */
public class Test {
  public static void main(String[] args) {
    /*
     * 构造方法私有化,不能够使用下面方式new对象
     */
    //LazySingleton lazySingleton=new LazySingleton();
    //使用实例获取方法来获取对象
    LazySingleton l1=LazySingleton.getInstance();
    LazySingleton l2=LazySingleton.getInstance();
    System.out.println(l1==l2);//true
  }
}
Copy after login

From above It can be seen that the two references of this test class are equal, which means that the two references point to the same object, and this also conforms to the singleton pattern standard. This is the end of the lazy man introduction.

2.3 The difference between the lazy style and the hungry style

The lazy style means that when there is no object, a singleton object will be created. When there is an object, no more objects will be created. , this may not be easy to understand, but if readers are interested in learning more, they can use breakpoints in eclipse to test, add breakpoints to the content within the if curly braces of the LazySingleton class, and then in the Test class, use debug operation, this can be easily reflected. An object is created the first time, but no object is created the second time.

Hungry Chinese style is implemented by using the final keyword to create the object. When the caller needs the instance object, the created instance can be obtained through the getInstance method.

2.4 Registered singleton class

The author is not very familiar with the registered singleton class. I have posted a piece of code on the Internet for your own reference. Readers are asked to study on their own.


import java.util.HashMap;
import java.util.Map;

/**
 * 登记式单例类
 * @author Administrator
 *
 */
public class RegisterSingleton {
 private static Map<String, RegisterSingleton> map = new HashMap<String, RegisterSingleton>();
 static {
  RegisterSingleton single = new RegisterSingleton();
  map.put(single.getClass().getName(), single);
 }

 /*
  * 保护的默认构造方法
  */
 protected RegisterSingleton() {
 }

 /*
  * 静态工厂方法,返还此类惟一的实例
  */
 public static RegisterSingleton getInstance(String name) {
  if (name == null) {
   name = RegisterSingleton.class.getName();
   System.out.println("name == null" + "--->name=" + name);
  }
  if (map.get(name) == null) {
   try {
    map.put(name, (RegisterSingleton) 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) {
  RegisterSingleton single3 = RegisterSingleton.getInstance(null);
  System.out.println(single3.about());
 }
}
Copy after login

The above is the detailed content of A brief introduction to the singleton pattern in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template