Java--设计模式(单例)

单例参考
单例与线程
参考
参考

并发测试
public class SingletonTest {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable(){
                @Override
                public void run(){
                    Singleton.getInstance();
                }
            }).start();
        }
    }
}
单例模式

1、懒汉式(线程不安全)

// 这种写法起到了Lazy Loading(延迟加载)的效果,但是只能在单线程下使用。
// 若多线程时,线程1进入了if(singleton==null),还没来得及往下执行,线程2也通过了这个判断语句,这时便会产生多个实例。
public class Singleton{
	private Singleton(){}
	private static Singleton instance;
	public static Singleton getInstance(){
		if(instance==null){
			System.out.println(instance);
			instance = new Singleton();
		}
		System.out.println(instance.hashCode());
		return instance ;
	}
}

2、懒汉式(线程不安全)(同步代码块)

// 跟第1种情形一致,多线程时,线程1进入了if(singleton==null),还未来得及往下执行,线程2也通过了这个判断语句,这时便会产生多个实例。
public class Singleton{
	private Singleton(){}
	private static Singleton instance;
	public static Singleton getInstance(){
		if(instance==null){
			System.out.println(instance);
			synchronized(Singleton.class){
				instance = new Singleton();
			}
		}
		System.out.println(instance.hashCode());
		return instance;
	}
}

3、懒汉式(线程安全)(不建议使用)

// 优点:单例只有在使用时才被实例化,一定程度上节约了资源。
// 缺点:加入synchronized关键字,同步方法,效率低,造成不必要的同步开销。
public class Singleton{
	private Singleton(){}
	private static Singleton instance;
	public static synchronized Singleton getInstance(){
		if(instance==null){
			System.out.println(instance);
			instance = new Singleton();
		}
		System.out.println(instance.hashCode());
		return instance;
	}
}

4、饿汉式(线程安全)(静态常量)

// 优点:这种写法比较简单,就是在类装载的时候就完成实例化,避免了线程同步问题。
// 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading(延迟加载)的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class Singleton{
	private Singleton(){}
    private static Singleton instance = new Singleton();
    public static Singleton getInstance(){
        System.out.println(instance.hashCode());
        return instance;
    }
}

5、饿汉式(线程安全)(静态代码块)

// 优点:这种写法比较简单,就是在类装载的时候就完成实例化,避免了线程同步问题。
// 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading(延迟加载)的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class Singleton{
	private Singleton(){}
	private static Singleton instance;
	static {
		instance = new Singleton();
	}
	public static Singleton getInstance(){
		System.out.println(instance.hashCode());
		return instance;
	}
}

6、双重校验锁(线程安全)(Double-Check)(推荐使用)

// 代码中,进行了两次if(singleton ==null)的检查,可以保证线程安全了。
// 实例化代码只用执行一次,后面再次访问时,判断if (singleton ==null),直接return实例化对象。
// 优点:线程安全;延迟加载;效率较高。
// 缺点:第一次加载稍慢,由于Java内存模型一些原因偶尔会失败,在高并发环境下也有一定的缺陷,但概率很小。
public class Singleton{
	private Singleton(){}
	private volatile static Singleton instance;
	public static Singleton getInstance(){
		if(instance==null){
			System.out.println(instance);
			synchronized(Singleton.class){
				if(instance==null){
					System.out.println("=========="+instance);
					instance = new Singleton();
				}
			}
		}
		System.out.println(instance.hashCode());
		return instance;
	}
}

7、静态内部类(线程安全)(推荐使用)

// 与饿汉式类似,又有不同。
// 两者都是采用了类装载的机制来保证初始化实例时只有一个线程。
// 不同的地方在饿汉式方式是只要Singleton类被装载就会实例化,没有Lazy-Loading的作用,而静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance方法,才会装载SingletonInstance类,从而完成Singleton的实例化。
// 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
// 优点:避免了线程不安全,延迟加载,效率高。
public class Singleton{
	private Singleton(){}
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();
    }
    public static Singleton getInstance(){
        System.out.println(SingletonHolder.instance.hashCode());
        return SingletonHolder.instance;
    }
}

8、枚举(线程安全)

public enum Singleton{
	INSTANCE;
	public void getInstance(){
		......
	}
}
// 当实例被写入到文件到反序列化成实例时,我们需要重写readResolve方法,以让实例唯一。
private Object readResolve() throws ObjectStreamException{
	return singleton;
}

9、容器

// 在程序的初始化,将多个单例类型注入到一个统一管理的类中,使用时通过key来获取对应类型的对象,这种方式使得我们可以管理多种类型的单例,并且在使用时可以通过统一的接口进行操作。
// 这种方式是利用了Map的key唯一性来保证单例。
public class SingletonManager{
	private SingletonManager(){}
	private static Map<String, Object> map= new HashMap<>();
	public static void setHashMap(String key, Object instance){
		if(!map.containsKey(key)){
			map.put(key, instance);
		}
	}
	public static Object getInstance(String key){
		System.out.println(map.get(key).hashCode());
		return map.get(key);
	}
}
适用场合

1、需要频繁的进行创建和销毁的对象;
2、创建对象时耗时过多或耗费资源过多,但又经常用到的对象;
3、工具类对象;
4、频繁访问数据库或文件的对象。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你默然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值