current position:Home>[one Java design pattern per day (3)] - singleton pattern

[one Java design pattern per day (3)] - singleton pattern

2022-01-27 02:02:40 1 = King

The singleton pattern yes Java One of the simplest design patterns in . This type of design pattern is a creation pattern , A class has only one instance , And this class can create a pattern of this instance by itself .

The singleton pattern is as follows 3 Characteristics :

  • A singleton class has only one instance object ;
  • The singleton object must be created by the singleton class itself ;
  • The singleton class provides a global access point to access the singleton .

There are usually two ways to implement singleton mode : Slacker type 、 Hungry Chinese style

Slacker type

Lazy doesn't generate instances when the class is loaded , Only when the first call getlnstance Method to create the singleton .

// Slacker type 
public class LazySingle {
    
    private static LazySingle instance;

    private LazySingle(){
    }

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

        return instance;
    }
}

Hungry Chinese style

In the hungry Chinese formula, once the class is loaded, a singleton is created , Make sure to call getInstance The single example before the method already exists .

// Hungry Chinese style 
public class HungrySingle {
    

    private final static HungrySingle instance = new HungrySingle();

    private HungrySingle(){
    }

    public static HungrySingle getInstance(){
    
        return instance;
    }
}

test

public class SingleMain {
    
    public static void main(String[] args) {
    
        LazySingle lazySingle1 = LazySingle.getInstance();
        LazySingle lazySingle2 = LazySingle.getInstance();

        System.out.println(" The first object created lazily :" + lazySingle1);
        System.out.println(" The second object created lazily :" + lazySingle2);
        System.out.println(lazySingle1 == lazySingle2);

        HungrySingle hungrySingle1 = HungrySingle.getInstance();
        HungrySingle hungrySingle2 = HungrySingle.getInstance();

        System.out.println(" The first object created in starving Han style :" + hungrySingle1);
        System.out.println(" The second object created in starvation :" + hungrySingle2);
        System.out.println(hungrySingle1 == hungrySingle2);

    }
}

 Insert picture description here
You can see , Whether lazy or hungry, the objects created many times are exactly the same , This shows that the singleton pattern only creates one instance .

copyright notice
author[1 = King],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270202379452.html

Random recommended