所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例, 并且该类只提供一个取得其对象实例的方法(静态方法)。
比如 Hibernate 的 SessionFactory,它充当数据存储源的代理,并负责创建 Session 对象。SessionFactory 并不是轻量级的,一般情况下,一个项目通常只需要一个 SessionFactory 就够,这是就会使用到单例模式。
其实单例就是那些很明显的使用场合,没有之前学习的那些模式所使用的复杂场景,只要你需要使用单例,那你就使用单例,简单易理解。
单例模式有7种方式:
1) 饿汉式(静态常量)
2) 饿汉式(静态代码块)
3) 懒汉式(线程不安全)
4) 懒汉式(线程安全,同步方法)
5) 双重检查
6) 静态内部类
7) 枚举
package com.yckj.design.singleton;
import java.util.concurrent.*;
public class Singleton {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//test01();
//test02();
//test03();
//testUnsafe03();
//testUnsafe04();
//testSafe05();
//testSafe06();
//testSafe07();
//testSafe08();
//test09();
test10();
}
public static void test01(){
Singleton01 instance = Singleton01.getInstance();
Singleton01 instance2 = Singleton01.getInstance();
System.out.println(instance == instance2);
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
public static void test02(){
Singleton02 instance = Singleton02.getInstance();
Singleton02 instance2 = Singleton02.getInstance();
System.out.println(instance == instance2);
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
public static void test03(){
Singleton03 instance = Singleton03.getInstance();
Singleton03 instance2 = Singleton03.getInstance();
System.out.println(instance == instance2);
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
public static void testUnsafe03(){
new Thread(new LaySingleton()).start();
new Thread(new LaySingleton()).start();
}
public static void testUnsafe04() throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Singleton03> future1 = service.submit(new LaySingleton02());
Future<Singleton03> future2 = service.submit(new LaySingleton02());
Singleton03 instance01 = future1.get();
Singleton03 instance02 = future2.get();
service.shutdown();
System.out.println(instance01==instance02);
System.out.println(instance01.hashCode());
System.out.println(instance02.hashCode());
/**
* 上面的测试结果
* 第一次:
* false
* 1173230247
* 856419764
*
* 第二次:
* true
* 1173230247
* 1173230247
*/
}
public static void testSafe05(){
new Thread(new LaySingleton03()).start();
new Thread(new LaySingleton03()).start();
}
public static void testSafe06() throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Singleton04> future1 = service.submit(new LaySingleton04());
Future<Singleton04> future2 = service.submit(new LaySingleton04());
Singleton04 instance01 = future1.get();
Singleton04 instance02 = future2.get();
service.shutdown();
System.out.println(instance01==instance02);
System.out.println(instance01.hashCode());
System.out.println(instance02.hashCode());
}
public static void testSafe07(){
new Thread(new LaySingleton05()).start();
new Thread(new LaySingleton05()).start();
}
public static void testSafe08() throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Singleton05> future1 = service.submit(new LaySingleton06());
Future<Singleton05> future2 = service.submit(new LaySingleton06());
Singleton05 instance01 = future1.get();
Singleton05 instance02 = future2.get();
service.shutdown();
System.out.println(instance01==instance02);
System.out.println(instance01.hashCode());
System.out.println(instance02.hashCode());
}
public static void test09(){
Singleton06 instance = Singleton06.getInstance();
Singleton06 instance2 = Singleton06.getInstance();
System.out.println(instance == instance2);
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
public static void test10(){
Singleton07 instance = Singleton07.INSTANCE;
Singleton07 instance2 = Singleton07.INSTANCE;
System.out.println(instance == instance2);
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
//饿汉式
/**
* 1)优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
* 2)缺点:在类装载的时候就完成实例化,没有达到 Lazy Loading 的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费
* 3)这种方式基于 classloder 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,在单例模式中大多数都是调用 getInstance 方法, 但是导致类装载的原因有很多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 就没有达到 lazy loading 的效果
* 4)结论:这种单例模式可用,可能造成内存浪费
*/
class Singleton01 {
//创建对象实例
private static final Singleton01 instance = new Singleton01();
//构造私有化
private Singleton01() {
}
//提供公有静态方法 返回对象实例
public static Singleton01 getInstance() {
return instance;
}
}
/*==========================================================================================================================*/
//饿汉式 使用静态块创建单例
/**
* 优缺点说明:
* 1)这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。
* 2)结论:这种单例模式可用,但是可能造成内存浪费
*/
class Singleton02 {
private static Singleton02 instance;
static {
instance = new Singleton02();
}
//提供公有的静态方法,返回对象实例
public static Singleton02 getInstance() {
return instance;
}
}
/*==========================================================================================================================*/
//懒汉式 (线程不安全,通过LaySingleton和LaySingleton02 多线程测试 )
/**
*
* 优缺点说明:
* 1)起到了 Lazy Loading 的效果,但是只能在单线程下使用。
* 2)如果在多线程下,一个线程进入了 if (instance == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式
* 3)结论:在实际开发中,不要使用这种方式.
*
*/
class Singleton03 {
//创建对象实例
private static Singleton03 instance;
//构造私有化
private Singleton03() {
};
//提供公有静态方法,返回对象实例
public static Singleton03 getInstance() {
if (instance == null) {
instance = new Singleton03();
}
return instance;
}
}
class LaySingleton implements Runnable{
@Override
public void run() {
Singleton03 instance = Singleton03.getInstance();
System.out.println(instance.hashCode());
}
}
class LaySingleton02 implements Callable<Singleton03> {
@Override
public Singleton03 call() throws Exception {
Singleton03 instance = Singleton03.getInstance();
//System.out.println(instance.hashCode());
return instance;
}
}
/*==========================================================================================================================*/
//懒汉式 (线程安全,同步代码块 ,通过LaySingleton03和LaySingleton04 多线程测试 )
/**
*
* 1)解决了线程安全问题
* 2)效率太低了,每个线程在想获得类的实例时候,执行 getInstance()方法都要进行同步。
* 而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接 return 就行了。方法进行同步效率太低
* 3)结论:在实际开发中,不推荐使用这种方式
*
*/
class Singleton04{
//创建对象实例
private static Singleton04 instance;
//构造私有化
private Singleton04() {
};
//提供公有静态方法,返回对象实例 加入同步代码块解决线程安全问题
public static synchronized Singleton04 getInstance() {
if (instance == null) {
instance = new Singleton04();
}
return instance;
}
}
class LaySingleton03 implements Runnable{
@Override
public void run() {
Singleton04 instance = Singleton04.getInstance();
System.out.println(instance.hashCode());
}
}
class LaySingleton04 implements Callable<Singleton04> {
@Override
public Singleton04 call() throws Exception {
Singleton04 instance = Singleton04.getInstance();
//System.out.println(instance.hashCode());
return instance;
}
}
/*==========================================================================================================================*/
// 双重标准检查 懒汉式(线程安全,加入双重检查代码,解决线程安全问题 ,通过LaySingleton05和LaySingleton06 多线程测试 )
/**
* 优缺点说明:
* 1)Double-Check 概念是多线程开发中常使用到的,如代码中所示,我们进行了两次 if (instance == null)检查,这样就可以保证线程安全了。
* 2)这样,实例化代码只用执行一次,后面再次访问时,判断 if (instance == null),直接 return 实例化对象,也避免的反复进行方法同步.
* 3)线程安全;延迟加载;效率较高
* 4)结论:在实际开发中,推荐使用这种单例设计模式
*/
class Singleton05{
//创建对象实例
private static volatile Singleton05 instance;//保证多线程下变量的可见性
//构造私有化
private Singleton05() {
};
//提供公有静态方法,返回对象实例 加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
//同时保证了效率, 推荐使用
public static Singleton05 getInstance() {
if (instance == null) {//第一次判断
synchronized (Singleton05.class){
if (instance==null){//第二次判断
instance = new Singleton05();
}
}
}
return instance;
}
}
class LaySingleton05 implements Runnable{
@Override
public void run() {
Singleton05 instance = Singleton05.getInstance();
System.out.println(instance.hashCode());
}
}
class LaySingleton06 implements Callable<Singleton05> {
@Override
public Singleton05 call() throws Exception {
Singleton05 instance = Singleton05.getInstance();
//System.out.println(instance.hashCode());
return instance;
}
}
/*==========================================================================================================================*/
//静态内部类 创建
/**
*优缺点说明:
* 1)这种方式采用了类装载的机制来保证初始化实例时只有一个线程。
* 2)静态内部类方式在 Singleton06 类被装载时并不会立即实例化,而是在需要实例化时,调用 getInstance 方法,才会装载 SingletonInstance 类,从而完成 Singleton 的实例化。
* 3)类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
* 4)优点:避免了线程不安全,利用静态内部类特点实现延迟加载,效率高
* 5)结论:推荐使用.
*/
class Singleton06{
private static volatile Singleton06 instance;
//构造器私有化
private Singleton06() {
}
//写一个静态内部类,该类中有一个静态属性
private static class SingletonInstance {
private static final Singleton06 INSTANCE = new Singleton06();
}
//提供一个静态的公有方法,直接返回 SingletonInstance.INSTANCE
public static synchronized Singleton06 getInstance() {
return SingletonInstance.INSTANCE;
}
}
/*==========================================================================================================================*/
//枚举创建单例
/**
* 优缺点说明:
* 1)这借助 JDK1.5 中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。
* 2)结论:推荐使用
*/
enum Singleton07{
INSTANCE;
Singleton07() {
}
}