栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java设计模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java设计模式

目录

一、什么是单例模式?

1、概念

2、实现要点

二、单例模式分类

 三、代码实现

1、饿汉式

1.1静态常量

1.2静态代码块

2、懒汉式

2.1线程不安全

2.2同步代码块(线程不安全)

2.3同步方法(线程安全)

3、双重检验锁(推荐)

4、静态内部类(推荐)

5、枚举(推荐)


一、什么是单例模式?

1、概念

在整个软件中,某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法

2、实现要点
  • 构造器私有化
  • 类的内部创建对象实例
  • 对外暴漏一个静态方法,返回实例对象

二、单例模式分类

 三、代码实现

1、饿汉式

1.1静态常量
public class Singleton {
    
    private Singleton() {}
    
    private static Singleton instance = new Singleton();
    
    public static Singleton getInstance() {
        return instance;
    }
}

1.2静态代码块
public class Singleton {
    
    private static Singleton instance; 
    
    static {
        instance = new Singleton();
    }
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return instance;
    }
}

2、懒汉式

2.1线程不安全
public class Singleton {
    
    private static Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

2.2同步代码块(线程不安全)
public class Singleton {
    
    private Singleton() {}
    
    private static Singleton instance;
    
    public static Singleton getInstance() {
        
        if (instance == null) {
            synchronized (Singleton.class) {
                
                instance = new Singleton();
                
            }
        }
        return  instance;
    }
}

2.3同步方法(线程安全)
public class Singleton {
    
    private static Singleton instance;
    
    private Singleton() {}
    
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

3、双重检验锁(推荐)
public class Singleton {
    
    private Singleton() {}
    
    private static volatile Singleton instance;
    
    public static Singleton getInstance() {
        
        if (instance == null) {
            synchronized (Singleton.class) {
                
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return  instance;
    }
}

4、静态内部类(推荐)
public class Singleton {
    
    private Singleton() {}
    
    private static class SingletonHolder {
        
        private static final Singleton INSTANCE = new Singleton();
    }
    
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

5、枚举(推荐)
public enum Singleton {
    INSTANCE
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号