java实现单例

将类的构造函数声明为private,只能在类内通过new Test()创建对象,在类内实现getInstance() 函数,实现new Test()创建对象。
下面为实现代码:

/**
 * @Description:Java实现单例
 * @author: 诗人的情人
 * @Date: 8:56 上午 2019/10/20
 */
public class JustForTest {
    public static void main(String[] args) {
        Test.getInstance().fun();
        Test.getInstance().fun();
    }
}

class Test{
    private volatile static Test instance;
    public static Test getInstance() {
        if (instance == null) {
            synchronized (Test.class) {
                if (instance == null) {
                    instance = new Test();
                }
            }
        }
        return instance;
    }
    private Test() {
        System.out.println("调用构造函数");
    }
    public static void fun() {
        System.out.println("调用fun");
    }
}

输出:

调用构造函数
调用fun
调用fun

Process finished with exit code 0

从输出结果可以看到:调用了两次fun()函数,构造函数只调用了一次。

代码很简单,记录一下自己的成长过程吧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值