Java singleton pattern instance brief

  • 2020-04-01 03:28:05
  • OfStack

This article illustrates the singleton pattern in Java, a very important concept in Java programming. Share with you for your reference. Specific analysis is as follows:

The monad pattern is to provide only one instance to the outside world in the whole application process, that is, there is only one instance when the application, so that there is no need to repeatedly create instances . At his request, then, look at the following code for the simplest singleton:


public class Singleton {
  private static Singleton single = new Singleton();
  
  private Singleton(){
    
  }
  
  public static Singleton getSingletonInstance(){
    return single;
  }
}

Through this code, we found that to implement the Singleton instance of the class, must through the constructor, but he's constructor is private, so I can't realize his instantiated in the other class, but can be by getSingletonInstance method, can return a single instance, because he is a public static function, can be invoked by other classes. This is a simple singleton pattern. You can also implement the single construct in the getSingletonInstance method.

Summarize the characteristics of a single example model:

1. The constructor is private.

2. There is a static application instance of private.

There is a static public method that returns an instance of that class.

In fact, these three characteristics are entirely determined by the requirements of the singleton pattern.

I hope this article will be helpful to your Java programming study.


Related articles: