Home  >  Article  >  Java  >  How to implement the Baohan pattern in java singleton

How to implement the Baohan pattern in java singleton

WBOY
WBOYforward
2023-05-16 21:52:331392browse

Instructions for use

1. Baohan is the singleton pattern with the most variations.

2. The core of Baohan mode is lazy loading. The advantage is that it starts quickly and saves resources until the instance is accessed for the first time. The small disadvantage of cases that require initialization is that it is troublesome to write. The disadvantage is that the thread is unsafe and the if statement has race conditions.

Example

//饱汉
//UnThreadSafe
public class Singleton1 {
    private static Singletion1 singleton = null;
    
    private Singleton1() {
    }
    
    public static Singleton1 getInstance() {
        if (singleton == null) {
            singleton = new Singleton1();
        }
        return singleton;
    }
}

The above is the detailed content of How to implement the Baohan pattern in java singleton. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete