单例模式

单例模式:确保一个类只有一个实例,并提供一个全局访问点。

1、饿汉式单例模式:饿汉式单例类在自己被加载时就将自己实例化。可以在JAVA语言内实现,不容易在C++中实现,因为静态初始化在C++里没有固定的顺序。

public class EagerSingleton {
    private static final EagerSingleton INSTANCE = new EagerSingleton();

    public static EagerSingleton getInstance() {
        return INSTANCE;
    }

    private EagerSingleton() {  }
}

2、懒汉式单例类实现里对静态工厂方法使用了同步化,以处理多线程环境。

public class LazySingleton {
    private static LazySingleton instance;

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

    private LazySingleton() {}
}

懒汉式模式在多线程运用就必须在getInstance()前加上synchronized,但是实际中只需要第一次执行时需要同步,后面每次调用同步都是一种累赘。

3、双重检查加锁

public class DoubleLockSingleton {
    //volatile关键词确保:当instance变量被初始化成DoubleLockSingleton实例时,多个线程正确地处理instance变量
    private volatile static DoubleLockSingleton instance;

    private DoubleLockSingleton(){}

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

        return instance;
    }
}

4、枚举单例

public enum EnumSingleton {
    INSTANCE;

    private EnumSingleton(){}

    public void method1(){}
}
枚举从Java1.5开始才出现,这种单例机制,无偿提供了序列化机制,绝对防止多次实例化,即使是在面对复杂的序列化或者反射攻击的时候。
(来源于《Effective Java》第二版 P.15)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值