java 设计模式之单例模式学习

最近开始学习一些java 设计模式,就先从最基础简单好理解的单利模式开始。以下是对不同实现单利模式理解学习。

package com.dairuijie.controller;

/**
 * 
 * @author DRJYY 单利模式 懒汉模式 缺点:线程不安全 原因:当两个线程同时去做singleton == null 判断的时候 结果都是null
 *         这样导致实例化两个对象。
 */
public class LazySingleton {
	private static LazySingleton singleton;

	private LazySingleton() {
	}

	public static LazySingleton getInstance() {
		if (singleton == null) {
			singleton = new LazySingleton();
		}
		return singleton;
	}
}

/**
 * 
 * @author DRJYY 单利模式之懒汉线程安全模式 特点:线程安全 因为加上synchronized 关键字
 *         加锁了。这样不会导致两个都实例化。保证只有一个 缺点:加锁的效率 不是很高。
 */
public class LazySafeSingleton {
	private static LazySafeSingleton instance;

	private LazySafeSingleton() {
	}

	public static synchronized LazySafeSingleton getInstance() {
		if (instance == null) {
			instance = new LazySafeSingleton();
		}
		return instance;
	}
}

/**
 * 单利模式之饿汉模式
 * 
 * @author DRJYY 特点:没有线程安全问题,但是类加载的时候 他就会实例化,不管你有没有使用到该实例。
 */
public class HungrySingle {

	private static HungrySingle instance = new HungrySingle();

	private HungrySingle() {
	}

	public static HungrySingle getInstance() {
		return instance;
	}
}

/**
 * 单利模式 静态内部类实现 同一个类加载器是线程安全
 * 
 * @author DRJYY 特点:看似也是先new 对象 但是他与饿汉模式区别是,饿汉类加载就开始实例化,这个虽然类加载了,但是new 对象操作
 *         放到静态内部类中, 这个需要外部去调用getInstance 才会实例化对象。达到懒加载效果。
 */
public class Singleton {
	private static class InnerSingleton {
		private static final Singleton INSTANCE = new Singleton();
	}

	private Singleton() {
	}

	public static final Singleton getInstance() {
		return InnerSingleton.INSTANCE;
	}
}

/**
 * 单利模式 双重校验锁
 * @author DRJYY
 *特点:首先线程安全,效率在第二种基础上有提高。因为 他在同步之前会有一个判断 ,这样就会过滤到不等于null 线程。
 */
public class DoubleLockSingleton {
	private volatile static DoubleLockSingleton singleton;

	private DoubleLockSingleton() {
	}

	public static DoubleLockSingleton getSingleton() {
		if (singleton == null) {
			synchronized (DoubleLockSingleton.class) {
				if (singleton == null) {
					singleton = new DoubleLockSingleton();
				}
			}
		}
		return singleton;
	}
}


猜你喜欢

转载自blog.csdn.net/qq_29897369/article/details/79090883