单例模式

单例模式必须私有化构造器!

必须提供一个对外的公共的静态方法访问实例

饿汉式

// 饿汉式
// 优点:没有线程安全问题
// 缺点:提前实例化,暂用内存空间
public class HungerSingleton {

    private HungerSingleton(){};

    private static final HungerSingleton instance= new HungerSingleton();

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

懒汉式

// 懒汉式
// 优点:用到再加载,不占用内存

public class LazySingleton {// 缺点:有线程安全问题

    private LazySingleton(){};

    private static LazySingleton instance= null;

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

}


public class LazySingleton {// 缺点:多线程访问有安全问题

    private LazySingleton(){};

    private static LazySingleton instance= null;

    public static LazySingleton getInstance(){
        if(null==instance){
            // 多线程同时进入会重复创建
            synchronized (LazySingleton.class){
                instance= new LazySingleton();
            }
        }
        return instance;
    }

}

public class LazySingleton {// 使用双重验证保证只实例化一次

    private LazySingleton(){};

    private static LazySingleton instance= null;

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

}

静态内部类

// 静态内部类单例
public class StaticInnerSingleton {

    private StaticInnerSingleton(){};

    public static final StaticInnerSingleton getInstance(){
        return SingletonHandle.instance;
    }

    private static class SingletonHandle{
        private static final StaticInnerSingleton instance = new StaticInnerSingleton();
    }

}

防止反序列化

// 防止反序列化获取对象
public class ReflectSingleton implements Serializable {

    private ReflectSingleton(){};

    private static final ReflectSingleton instance = new ReflectSingleton();

    public static ReflectSingleton getInstance(){
        return instance;
    }


    // 防止反序列化获取
    // I/O流中读取时readResolve()会被调用
    // 替换在反序列化过程中创建的对象
    private Object readResolve() throws ObjectStreamException {
        return instance;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值