java 单实例的饿汉式和赖汉式的实现方式

Java单实例有两种实现方式:饿汉式和赖汉式

废话不多说直接上代码

package test;

import zb.main.domian.user;

public class user_instance_scope_single_hungry {
    //饿汉式
    private static user tom=new user();  //静态私有且实例化
    private user_instance_scope_single_hungry(){} //私有构造方法保证 
                                     //user_instance_scope_single_hungry类不能实例化
    public static user getTom(){  //只能通过该向外提供的方法获得user对象
        return tom;
    }


}
package test;

import zb.main.domian.user;

public class user_instance_scop_single_lazy {
    //赖汉式
    private static user lucy=null;  //私有 静态 不实例化
    private user_instance_scop_single_lazy(){}
    public static user getLucy(){
        if (lucy==null){ //判断是否为第一次使用,如为第一次使用lucy必为空则new一个
            lucy=new user();
        }
        return lucy;
    }
}
package test;

import zb.main.domian.user;

public class test {
    public static void main(String[] args) {
        //饿汉式
        user tom = user_instance_scope_single_hungry.getTom();
        user tom1 = user_instance_scope_single_hungry.getTom();
        System.out.println(tom);
        System.out.println(tom1);
        //赖加载 赖汉式
        user lucy = user_instance_scop_single_lazy.getLucy();
        user lucy1 = user_instance_scop_single_lazy.getLucy();
        System.out.println(lucy);
        System.out.println(lucy1);
    }
}

 这里有必要解释的是声明的user对象必须为私有静态类型只有这样才能保住它是单实例的

由上可看出饿汉式与赖汉式的实现区别无非就是饿汉式在装载时就实例化了,

而赖汉式在第一次使用时才实例化

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值