单例模式

单例模式是设计模式的一种,分为饥饿式和懒汉式两种,什么地方需要它呢?比如数据库实例,连接池等。下面是实现:

1.饥饿式:

只需要两步即可,代码如下:

/*
 * 饥饿模式
 */
public class SingleInstance {
    //1.建一个私有的构造函数,不让外部直接new对象实例
    private SingleInstance(){
    }
    //2.在此类里建一个类的实例,用静态方法返回
    private static SingleInstance instance = new SingleInstance();
    public static SingleInstance getInstance(){
        return instance; 
    }
}

然后进行测试:

public class Test {

    public static void main(String[] args) {
        SingleInstance s1 = SingleInstance.getInstance();
        SingleInstance s2 = SingleInstance.getInstance();
        if(s1==s2){
            System.out.println("s1==s2");
        }else{
            System.out.println("s1!=s2");
        }
    }
}

运行结果:
相等

2.接下来是懒汉式:

/*
 * 懒汉模式
 */
public class SingleInstance {
    //1.建一个私有的构造函数,不让外部直接new对象实例
    private SingleInstance(){
    }
    //2.在此类里声明一个类的实例,在用户调用类时才生成对象
    private static SingleInstance instance;
    public static SingleInstance getInstance(){
        if(instance==null){
            instance = new SingleInstance();
        }
        return instance; 
    }
}

当然测试代码和运行结果一样。

3.他们的区别:

饥饿式:加载类时较慢,运行时获取对象的速度快,且线程安全;
懒汉式:刚好相反,加载时快,运行时慢,线程不安全。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值