单例模式及其扩展

设计模式之禅学习——单例模式

1、单例模式应该是设计模式最简单的一种了,我认为,单例模式最基本的原理就是创建一个私有的构造函数,然后在该类中就生成一个该类的实例,并且通过一个静态方法返回该实例,那么当其他类应用该类时,使用的始终是一个该类的实例。

2、单例模式分为恶汉式和懒汉式。

3、恶汉式单例通用代码如下:

package com.wang.singletonPattern;

/**
 * 恶汉式单例
 * @author HeJW
 *
 */
public class Singleton1 {
	
	private static final Singleton1 singleton1 = new Singleton1();
	
	private Singleton1(){
		System.out.println("创建Singleton1实例");
	}
	
	/*
	 * 当其他类要使用该类是,通过调用该方法,得到该类的实例,并且得到的永远都是这一个
	 */
	public static Singleton1 getSingleton1(){
		return singleton1;
	}
	
}

 4、懒汉式单例代码如下:

package com.wang.singletonPattern;

/**
 * 懒汉式单例
 * @author HeJW
 *
 */
public class Singleton2 {

	private static Singleton2 singleton2 = null;
	
	private Singleton2(){
		System.out.println("创建Singleton2实例");
	}
	
	//如果不加synchronized关键字,线程不安全
	public static synchronized Singleton2 getSingleton2(){
		
		if( singleton2 == null ){
			singleton2 = new Singleton2();
		}
		
		return singleton2;
	}
	
}

 懒汉式单例记得要加synchronized关键字,如果不加synchronized关键字,线程不安全。如果一个A执行到

singleton2 = new Singleton2();

 ,但还没有获得对象(对象初始化是需要时间的),第二个线程B也在执行,执行到

singleton2 == null

 判断,那么线程B得到的判断也为真,于是线程B也创建了一个实例,这样就导致两个线程创建了两个对象,所以线程不安全,只能加上synchronized关键字。

5、单例模式扩展,生成指定数量的实例,代码如下:

package com.wang.singletonPattern;

import java.util.ArrayList;
import java.util.Random;

/**
 * 单例模式扩展,生成指定数量的实例
 * @author HeJW
 *
 */
public class SingletonDevelop {

	//定义最多能生产两个实例
	private static int maxNum = 2;
	
	//定义一个列表,容纳多有的实例
	private static ArrayList<SingletonDevelop> singletonDeveloplist = new ArrayList<SingletonDevelop>();
	
	//产生指定数量的实例对象
	static{
		for( int i=0; i<maxNum; i++ ){
			singletonDeveloplist.add(new SingletonDevelop());
		}
	}
	
	private SingletonDevelop(){
		System.out.println("创建SingletonDevelop实例");
	}
	
	//得到随机的SingletonDevelop实例
	public static SingletonDevelop SingletonDevelop(){
		Random randrom = new Random();
		int singletonDevelopNum = randrom.nextInt(maxNum);
		return singletonDeveloplist.get(singletonDevelopNum);
	}
	
}

 

猜你喜欢

转载自hejiawangjava.iteye.com/blog/2233853
今日推荐