实现单例模式的五种方法

单例模式:某个类只存在一个对象实例

方法1:饿汉式

class HungryMan{

    //1.私有化类的构造器
    private HungryMan(){}
    //2.内部创见类的对象
    //4.要求此对象也必须声明为静态的
    private static HungryMan instance = new HungryMan();
    //3.提供公共的静态的方法,返回类的对象。
    public static HungryMan getInstance(){
        return instance;
    }
}

方法2、3:懒汉式

class LazyMan{

    //1.私有化类的构造器
    private LazyMan(){}
    //2.声明当前类对象,没有初始化。
    //4.此对象也必须声明为 static 的
    private static LazyMan instance = null;
    //3.提供公共的静态的方法,返回类的对象。
    //方式2:线程要一个一个的去获取对象
//    public static synchronized LazyMan getInstance() {//synchronized也可以写在方法里,形成同步代码块
//        if (instance == null) {
//            instance = new LazyMan();
//        }
//        return instance;
//    }
    //方式3:使用了double-check,可以多线程同时并发访问获取对象
    public static LazyMan getInstance(){
        if(instance == null) {
            synchronized (LazyMan.class) {
                if (instance == null) {
                    instance = new LazyMan();
                }
            }
        }
        return instance;
    }
}

方法4:内部静态类,外部类初次加载,会初始化静态变量、静态代码块、静态方法,但不会加载内部类和静态内部类。

class InnerStaticClass {

    private InnerStaticClass() {}
    public static InnerStaticClass getInstance() {
        return InnerStaticClassFactory.instance;
    }
    private static class InnerStaticClassFactory {
        private static InnerStaticClass instance = new InnerStaticClass();
    }

}

方法5:枚举

enum Enumeration {
    INSTANCE;
    public void doSomething() {
        System.out.println("doSomething");
    }
}

测试:

public class BankTest {
    public static void main(String[] args) {

        HungryMan hungryMan1 = HungryMan.getInstance();
        HungryMan hungryMan2 = HungryMan.getInstance();

        LazyMan lazyMan1 = LazyMan.getInstance();
        LazyMan lazyMan2 = LazyMan.getInstance();

        InnerStaticClass innerStaticClass1 = InnerStaticClass.getInstance();
        InnerStaticClass innerStaticClass2 = InnerStaticClass.getInstance();

        Enumeration.INSTANCE.doSomething();

        System.out.println(hungryMan1 == hungryMan2);
        System.out.println(lazyMan1 == lazyMan2);
        System.out.println(innerStaticClass1 == innerStaticClass2);

    }

}

结果:

doSomething
true
true
true

Process finished with exit code 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值