search
HomeJavajavaTutorialA brief introduction to the singleton pattern in Java

A brief introduction to the singleton pattern in Java

Oct 12, 2017 am 10:17 AM
javaintroduceSimple

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;
  }
}

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
  }
}

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;
  }
}

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
  }
}

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());
 }
}

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!

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
What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Explain the difference between platform independence and cross-platform development.Explain the difference between platform independence and cross-platform development.Apr 26, 2025 am 12:08 AM

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?Apr 26, 2025 am 12:02 AM

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools