java 单例模式

单例模式就是你不用再去new对象,而是有你调用函数,函数中去帮你创建对象,为什么不自己new呢,要调用函数不是麻烦了吗?

因为你每次new对象的时候,虽然都是同一个类的对象,但你每次new的时候,在内存中都每个你new对象对相应内存空间是不一样的,也就是说会占用多个内存空间,但是如果每次申请对象的时候先判断该对象是否存在,如果存在就使用这个对象,那这样的话就节省内存空间,但你每次想申请对象的时候不能都写一堆代码去判断对象是否存在,所以就写成一个函数,函数功能判断对象是否存在,存在就返回现有对象,不存在就创建一个对象返回,也就是所谓的单例模式。

单例模式很简单,也很复杂,看一看例子吧

下面给一个基础的例子

public class test {
     private  static test instance = new test();
     
     private test(){};  //构造函数为 private,该类就不能被实例化
     
     public static test getinstance()
     {
    return instance;
     }
     
     public void test_fun()
     {
    System.out.println("实例化成功");
     }
}


public class test_demo {
       public static void main(String [] args)
       {
      //test t = new test();  不可以,因为test函数的构造函数为private,所以不能实例化
      
      //应该这么用
      
      test t = test.getinstance();
      
           t.test_fun();      
       }
}

输出结果为实例化成功


单例实现有好多种方法,所以说有点复杂。

第一个  懒汉式:线程不安全
     

public class test {
     private  static test instance ;
     
     private test(){};  //构造函数为 private,该类就不能被实例化
     
     public static test getinstance()
     {
    if(instance == null)
    {
    instance = new test();
    }
    return instance;
     }
}


这种比较简单,但是是线程不安全的,因为方法没有加锁,不支持多线程


第二种  懒汉式:线程安全

public class test {
     private  static test instance ;
     
     private test(){};  //构造函数为 private,该类就不能被实例化
     
     public static synchronized test getinstance()
     {
    if(instance == null)
    {
    instance = new test();

    }
    return instance;
     }
}


就是在上一方法上的getinstance方法上加了一个synchronized关键字,加锁功能,但是加锁解锁本身很浪费效率,所以这个线程安全,但是效率可能差一点


第三种   饿汉式

public class test {
     private  static test instance = new test();
     
     private test(){};  //构造函数为 private,该类就不能被实例化
     
     public static test getinstance()
     {
    return instance;
     }
}


这种方法不加锁,所以效率提高,但是每次类加载的时候就执行创建对象操作,浪费内存


第四种   双重校验锁

public class test {
     private volatile static test instance ;
     
     private test(){};  //构造函数为 private,该类就不能被实例化
     
     public static test getinstance()
     {
    if (instance == null) {  
           synchronized (test.class) {  
           if (instance == null) {  
               instance = new test();  
           }  
           }  
       }  
    return instance;  
     }
}












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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值