设计模式-单例模式


/*
 * 饿汉式
 * 避免多线程的问题,在类被装载时就实例化对象
 * */
public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {
        System.out.println("无法直接new对象");
    }

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

/*
 * 饿汉式
 * 在静态代码块中实例化对象,也是在类被装载时实例化对象
 * */
public class Singleton2 {
    private static Singleton2 singleton = null;
    static {
        singleton = new Singleton2();
    }

    private Singleton2() {
        System.out.println("无法直接实例化对象");
    }

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

/*
* 懒汉式
* 线程不安全,在未前一个线程准备实例化前可能有一个线程立即进入判断
* */
public class Singleton3 {
    private static Singleton3 singleton = null;

    private Singleton3() {
        System.out.println("无法直接实例化对象");
    }

    public static Singleton3 getInstance() {
        if(singleton == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            singleton = new Singleton3();
        }
        return singleton;
    }

}

/*
* 懒汉式
* 用同步锁锁定函数,线程安全
* */
public class Singleton4 {
    private static Singleton4 singleton = null;

    private Singleton4() {
        System.out.println("无法直接实例化对象");
    }

    public static synchronized Singleton4 getInstance() {
        if(singleton == null) {
            singleton = new Singleton4();
        }
        return singleton;
    }
}

/*
* 静态内部类,懒汉式
* 静态内部类只有第一次被使用时才被装载,也就是第一次调用getInstance时才被装载
*
*
* */

public class Singleton5 {
    private static class SingletonHoler {
        private static final Singleton5 singleton = new Singleton5();
    }

    private Singleton5() {
        System.out.println("无法直接实例化对象");
    }

    public static final Singleton5 getInstance() {
        return SingletonHoler.singleton;
    }

}

/*
 * 双重校验锁--jdk1.5
 * */
public class Singleton6 {
    private volatile static Singleton6 singleton = null;

    private Singleton6() {
        System.out.println("无法直接实例化对象");
    }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值