3. Singleton mode of design mode

Singleton pattern: ensures that a class has only one instance and provides a global access point

1. Hungry Chinese style singleton

public class HungrySingleton {
    
    
    private static HungrySingleton instance = new HungrySingleton();

    private HungrySingleton() {
    
    };

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

2. Lazy Singleton

public class LazySingleton {
    
    
    private static LazySingleton instance;

    private LazySingleton() {
    
    };

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

3. Double check lock implementation

public class DoubleCheckedSingleton {
    
    
    private volatile static DoubleCheckedSingleton instance;

    private DoubleCheckedSingleton() {
    
    };

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

4. Static inner class implementation

public class Singleton {
    
    

    private Singleton() {
    
    };

    public static Singleton getInstance() {
    
    
        return SingletonHolder.singleton;
    }

    private static class SingletonHolder {
    
    
        private static final Singleton singleton = new Singleton();
    }
}

5. Implementation by enumeration

public class EnumSingleton {
    
    

    public enum ResourceInstance {
    
    
        INSTANCE;
        private Resource resource;

        ResourceInstance() {
    
    
            this.resource = new Resource();
        }

        public Resource getResource() {
    
    
            return this.resource;
        }
    }
}

class Resource {
    
    }

Guess you like

Origin blog.csdn.net/SJshenjian/article/details/130874430