其他分享
首页 > 其他分享> > 单例模式

单例模式

作者:互联网

类型:创建型

定义:一个类在全局只能有一个对象实例

实现需要考虑的地方:

饿汉式

在类加载时就初始化好单例对象。

public class IdGenerator {
    private AtomicLong id = new AtomicLong();
    private static final IdGenerator instance = new IdGenerator();

    private IdGenerator() {}

    public static IdGenerator getInstance() {
        return instance;
    }
    
    public long getId() {
        return id.getAndIncrement();
    }
}

懒汉式

在第一次获取单例时创建对象。

public class IdGenerator {
    private AtomicLong id = new AtomicLong();
    private static IdGenerator instance;

    private IdGenerator() {}

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

    public long getId() {
        return id.getAndIncrement();
    }
}

双重检测

在懒汉式下提高了代码效率:

public class IdGenerator {
    private AtomicLong id = new AtomicLong();
    private static IdGenerator instance;

    private IdGenerator() {}

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

    public long getId() {
        return id.getAndIncrement();
    }
}

静态内部类

只有在获取单例使,才会触发静态内部类的加载:

public class IdGenerator {
    private AtomicLong id = new AtomicLong();
    private static IdGenerator instance;

    private IdGenerator() {}

    public static IdGenerator getInstance() {
        return SingletonHolder.instance;
    }
    
    private static class SingletonHolder {
        private static final IdGenerator instance = new IdGenerator();
    }

    public long getId() {
        return id.getAndIncrement();
    }
}

枚举

通过枚举保证线程安全和全局唯一性。

public enum IdGenerator {
    INSTANCE;

    private final AtomicLong id = new AtomicLong();
    
    public long getId() {
        return id.getAndIncrement();
    }
}

参阅

标签:IdGenerator,private,id,instance,模式,单例,AtomicLong,public
来源: https://www.cnblogs.com/liaozibo/p/singleton-pattern.html