java如何实现单例设计模式

163 篇文章 0 订阅

单例模式的几种实现方式:

一:饿汉式单例

方式一:枚举方式获得单例对象

方式二:静态属性获得单例对象

方式三:静态方法获得单例对象

二:懒汉式单例

方式一:静态方法获得单例对象(线程安全)

方式二:内部类方式去获取单例对象

示例:

恶汉式:方式一

enum Singleton{

INSTANCE;//单例

}

恶汉式:方式二

class Singleton{

public static final Singleton INSTANCE = new Singleton();//单例

private Singleton(){}

}

恶汉式:方式三

class Singleton{

private static final Singleton INSTANCE = new Singleton();//单例

private Singleton(){}

public static Singleton getInstance(){

return INSTANCE;

}

}

懒汉式:方式一

class Singleton{

private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){

//存在线程安全问题(多线程的时候,不一定是单例)

/*if(null == instance){

instance = new Singleton();

}

return instance;*/

if(null == instance){  //提升代码效率,避免每一次都去走同步代码块

synchronized(Singleton.class){

if(null == instance){

instance = new Singleton();

}

return instance;

}

}

return instance;

}

}

}

懒汉式:方式二

class Singleton{

private Singleton(){}

private static class Inner{

public static final Singleton INSTANCE = new Singleton();

}

public static Singleton getInstance(){

return Inner.INSTANCE;

}

}

来源:微点阅读  https://www.weidianyuedu.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值