In real life, we often find that some things are unique. For example, a store has one and only one owner.

In Java, we create the store class and the boss class, and instantiate the boss instance in the store.

Public class Shop {public static void main(String[] args) {Master master1 = new Master(); Master master2 = new Master(); }}Copy the code

The problem is that you can still instantiate multiple owners in a single store class, which doesn’t meet the requirements.

The singleton pattern is designed to solve this problem by ensuring that one and only one instance exists.

Create a unique private static instance in the boss class (instantiate itself first in the singleton class) and make the constructor private so that no one else can instantiate the class. Finally, write a public static method that returns an instance.

Private static Master Master = new Master(); private static Master Master = new Master(); Public static Master getInstance() {public static Master getInstance() {public static Master getInstance() {public static Master getInstance() { return master; }}Copy the code

You can then access it using the getInstance method:

Public class Shop {public static void main(String[] args) {Master m = master.getinstance (); }}Copy the code

In this way, there is always only one instance of the boss we call, which is the unique instance in the Master class.