单例模式--各种实现方式详解

1、饿汉模式

//饿汉模式
public class singleton1 {
    private static singleton1 singleton = new singleton1();

    /*
     * private static singleton1 singleton;
     * static{
     *   singleton = new singleton1();
     * }
     */

    private singleton1(){

    }

    public static singleton1 getInstance(){
        return singleton;
    }

}

饿汉模式简单直接,但是有一点不好就是在初始化的时候太早了,没有做到什么时候用什么时候创建。
2、懒汉模式

//懒汉模式
public class singleton2 {
    private static volatile singleton2 singleton = null;

    private singleton2(){

    }

    public static singleton2 getInstance(){
        if(singleton == null)
            singleton = new singleton2();
        return singleton;

    }


}

懒汉模式这种实现是非线程安全的。单线程运行还可以。多线程就问题很大了。
3、Synchronized-懒汉模式

//加锁解决懒汉模式多线程不安全的问题
//synchronized 粒度有点大,加在方法上是串行的。
public class singleton3 {
    private static volatile singleton3 singleton = null;

    private singleton3(){

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

}

锁的粒度很大,java反射同样可以生成多个实例。
4、DCL-双检锁懒汉模式–避免反射的漏洞

//DCL双检锁机制实现懒汉模式的线程安全
public class singleton4 {
    private static volatile singleton4 singleton = null;

    private singleton4(){

    }

    public static singleton4 getInstance(){
        if(singleton == null)
            synchronized(singleton4.class){
                if(singleton == null)
                    singleton = new singleton4();

            }
        return singleton;

    }
}

5、使用Enum来实现单例

//枚举类型实现单例模式
public class singleton5 {

    private enum singletontest{
        getsingleton;
        private static singletontest singleton;

        private singletontest(){
        }

        public Connection getInstance(){
            if (singleton == null){
//              singleton =传进一个比如connection的实例 
            }
            return null;
        }
    }

    public static Connection getinstance(){
        return singletontest.getsingleton.getInstance();

    }

}

6、内部类实现单例模式

public class singleton6 {

    private static class singleton1{
        private static singleton6 singleton = new singleton6();
    }

    private singleton6(){

    }

    public static singleton6 getInstance(){
        return singleton6.singleton1.singleton;
    }

}

最后这个到底是不是能够防止反射,我个人认为是可以的,因为在反射中没有考虑到内部类的情况,只考虑了方法和字段。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值