单例模式---Java实现

单例模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:

1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。

优点:由于在一个系统,一个类经常被使用在不同的地方,通过单例模式,可以避免多次创建多个实例,从而节约系统资源。

懒汉模式:

//懒汉模式
public finall class Singleton{
    private static Singleton instance = null;
    private Singleton(){ };
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }

}
//加锁 解决线程同步问题
public finall class Singleton{
    private static Singleton instance = null;
    private Singleton(){ };
    public static synchorized Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }

}
//双重校验锁  解决性能问题
public finall class Singleton{
    private static Singleton instance = null;
    private Singleton(){ };
    public static synchorized Singleton getInstance(){
    if(instance == null){
        synchorized(Singleton.class){
         if(instance == null){
            instance = new Singleton();
         }
        }
    }
        return instance;
    }
    
}

饿汉模式

//饿汉模式  以空间换时间  一开始就创建实例
public class Singleton2 {  
    
    private static Singleton2 instance = new Singleton;//自行创建实例 
    private Singleton2(){ }  //构造函数
    public static Singleton2 getInstance(){
     //通过该函数向整个系统提供实例   
        return instance;
    }
}

饿汉模式的优点是:
可以保证多线程情况下实例的唯一性,而且getInstance直接返回唯一实例,性能非常高。
缺点:在类成员变量比较多,或变量比较大的情况下,这种模式可能会在没有使用类对象的情况下,一直占用堆内存。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值