Design Patterns (1)------Singleton Pattern

introduce

This pattern involves only a single class that is responsible for creating its own objects and ensures that only one object is created.

A singleton has only one instance;
a singleton class must create its own unique instance;
a singleton class must provide this unique instance to other objects;

Classification

Since today's programming models are based on multithreading, only a few implementations of thread safety are described here.

lazy type

The object is only created when it is called for the first time, which belongs to lazy loading (Lazy-Init), which saves a certain amount of memory, but the performance will be lower due to the need to increase the synchronization lock.

public class LazySingleton {

    private static LazySingleton lazySingleton;

    public static synchronized LazySingleton getInstance() {
        if (lazySingleton == null) {
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }

}

hungry man

Objects are created when the class is loaded, which does not belong to lazy loading (Lazy-Init), so there will be a certain amount of memory loss, but synchronization locks are not applicable, so the performance will be higher.

public class HungrySingleton {

    private static HungrySingleton hungrySingleton = new HungrySingleton();

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

}

double lock

The double lock mechanism is a lazy loading (Lazy-Init), which can not only ensure thread safety, but also not lose too much performance.

public class DubbleLockSingleton {

    private static volatile DubbleLockSingleton dubbleLockSingleton;

    public static DubbleLockSingleton getInstance() {
        if (dubbleLockSingleton == null) {
            synchronized (DubbleLockSingleton.class) {
                if (dubbleLockSingleton == null) {
                    dubbleLockSingleton = new DubbleLockSingleton();
                }
            }
        }
        return dubbleLockSingleton;
    }

}

static inner type

It is simpler to implement than double locks, and it saves more resources than the hungry type, because the object is created when the inner class is called.

public class StaticInternalSingleton {

    private static class StaticInternalSingletonHolder {

        private static StaticInternalSingleton INSTANCE = new StaticInternalSingleton();

    }

    public static StaticInternalSingleton getInstance() {

        return StaticInternalSingletonHolder.INSTANCE;

    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325958997&siteId=291194637