java设计模式之单例模式

单例模式我们很熟悉,而且网上也有很多文章,不过有很多文章都是不对的,所以今天来总结一下,如果大家想去看原理,推荐大家去看Java并发编程的艺术这本书,这个里面会有很多原理的东西

版本1

private static Singleton single = null;

//不对,会重复创建

public static Singleton getInstance() {

if (single == null) {

single = new Singleton();

}

return single;

}

版本2

//对,但是非常影响性能,不推荐

public static synchronized Singleton getInstance2() {

if (single == null) {

single = new Singleton();

}

return single;

}

版本3

//不对,会重复创建,具体分析可以去看书

public static Singleton getInstance3() {

if (single == null) {

synchronized (Singleton.class) {

if (single == null) {

single = new Singleton();

}

}

}

return single;

}

版本4

//正确,即时加载

private static Singleton instance5 = new Singleton();

public static Singleton getInstance5() {

return instance5;

}

版本5

//正确,用了volatile关键字

private static volatile Singleton instance;

public static Singleton getInstance4() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null) {

instance = new Singleton();

}

}

}

return instance;

}

版本6

//正确,延时加载

private static class InstanceHolder {

public static Singleton instance = new Singleton();

}

public static Singleton getInstance6() {

return InstanceHolder.instance;

}

版本7

//正确,推荐使用

创建一个枚举类

public enum SingleEunm {

INSTANCE;

private Singleton instance;

SingleEunm() {

instance = new Singleton();

}

public Singleton getInstance() {

return instance;

}

}

然后用SingleEunm.INSTANCE.getInstance();进行调用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这里对java中的单例模式进行一些简单的描述,并不对其进行过于深入的探讨,比如现在有一些帖子中有认为使用枚举创建的...
    spring_chicken阅读 311评论 0 0
  • 单利模式 定义 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 Singleton:负责创建Singlet...
    PeterHe888阅读 293评论 0 0
  • 前言 本文主要参考 那些年,我们一起写过的“单例模式”。 何为单例模式? 顾名思义,单例模式就是保证一个类仅有一个...
    tandeneck阅读 2,540评论 1 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399