Java 简明教程

Java - Singleton Class

Java Singleton Design Pattern

单例模式是 Java 中最简单的设计模式之一。此类设计模式属于创建模式,因为此模式提供了创建 object 的最佳方法之一。

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

Java Singleton Class

此模式包含一个单一类,该类负责创建对象,同时确保只创建一个对象。该类提供了一种访问其唯一对象的方法,可以直接访问该对象,而不必实例化该类的对象。

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

由于只有一个 Singleton 实例,Singleton 的任何实例字段都仅在每个类中出现一次,就像静态字段一样。Singleton 通常控制对资源的访问,例如数据库连接或套接字。

Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.

例如,如果只有数据库的一个连接许可证,或者 JDBC 驱动程序在多线程中遇到问题,Singleton 确保只进行一个连接,或一次只有一个线程可以访问该连接。

For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Advantages of Singleton Design Pattern

Singleton 设计模式节省内存,因为它只创建了一个对象实例,它还提供对其实例的全局访问。

Singleton design pattern saves memory because only one object instance is created and it also provides global access to its instance.

Use of Singleton Design Pattern

当您想创建一个只有一个实例的类时,可以使用 singleton 设计模式。它主要用于多线程,以创建多线程和数据库相关的应用程序。

The singleton design pattern is used when you want to create such a class that has only one instance. It is mainly used in multithreading to create multi-threaded and database-related applications.

使用 singleton 设计模式的一些设计:

Some of the designs where singleton design pattern is used:

  1. To create logger classes

  2. To create configuration management-related classes

  3. To create classes related to database connection pooling

  4. To create a class for the caching mechanism

Java Singleton Class/Design Pattern: Examples

Example 1

最简单的实现包含一个私有构造函数和一个用于保存其结果的字段,以及一个名为 getInstance() 的静态访问器方法。

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

可以在静态 initializer block 中分配私有字段,或者更简单地使用初始化器分配。然后 getInstance() 方法(必须为公有)只需返回此实例 −

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance −

package com.tutorialspoint;

class Singleton {

   private static Singleton singleton = new Singleton( );

   /* A private Constructor prevents any other
    * class from instantiating.
    */
   private Singleton() { }

   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }

   /* Other methods protected by singleton-ness */
   protected void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   }
}
public class Tester {

   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

如果您编译并执行上述程序,将得到以下结果 −

If you compile and execute the above program, you will get the following result −

demoMethod for singleton

Example 2

以下实现展示了一个典型的 Singleton 设计模式。在此示例中,ClassicSingleton 类维护对唯一 singleton 实例的静态引用,并从静态 getInstance() 方法返回该引用。

Following implementation shows a classic Singleton design pattern. In this example, the ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

在此,ClassicSingleton 类采用称为延迟实例化的技术来创建 singleton;因此,singleton 实例只在首次调用 getInstance() 方法时创建。此技术可确保只在需要时创建 singleton 实例。

Here, ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.

package com.tutorialspoint;

class ClassicSingleton {

   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }

   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }

   protected void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   }
}
public class Tester {

   public static void main(String[] args) {
      ClassicSingleton tmp = ClassicSingleton.getInstance( );
      tmp.demoMethod( );
   }
}

如果您编译并执行上述程序,将得到以下结果 −

If you compile and execute the above program, you will get the following result −

demoMethod for singleton

Example 3

以下实现演示了线程安全 Singleton 对象创建。在此示例中,ClassicSingleton 类维护对唯一 singleton 实例的静态引用,并从使用 synchronized 关键字使其成为线程安全的静态 getInstance() 方法中返回该引用。

Following implementation shows a threadsafe Singleton object creation. In this example, the ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method which we’ve made threadsafe using synchronized keyword.

class ClassicSingleton {

   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }

   public static synchronized ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }

   protected void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   }
}
public class Tester {

   public static void main(String[] args) {
      ClassicSingleton tmp = ClassicSingleton.getInstance( );
      tmp.demoMethod( );
   }
}

如果您编译并执行上述程序,将得到以下结果 −

If you compile and execute the above program, you will get the following result −

demoMethod for singleton