面试题复习-常用设计模式-单例模式

饿汉式:

package com.ajax.pattern.singleton;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Singleton {
    private static Singleton singleton = new Singleton();

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

懒汉式:

package com.ajax.pattern.singleton;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class SingletonEx {
    private static volatile SingletonEx instance = null;

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

枚举:——

posted @ 2019-08-02 18:45  疯狂阿贾克斯  阅读(177)  评论(0编辑  收藏  举报