Design Pattern 简明教程

Design Pattern - Singleton Pattern

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

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.

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

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.

Implementation

我们准备创建一个 SingleObject 类。SingleObject 类的构造函数为私有,并且有它自己的一个静态实例。

We’re going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.

SingleObject 类提供一个静态方法来将它的静态实例提供给外部世界。SingletonPatternDemo,我们的演示类将使用 SingleObject 类来获取一个 SingleObject 对象。

SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.

singleton pattern uml diagram

Step 1

创建单例类。

Create a Singleton Class.

SingleObject.java

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Step 2

获取 Singleton 类的唯一对象。

Get the only object from the singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}

Step 3

验证输出。

Verify the output.

Hello World!