单例模式

数学与逻辑学中,singleton定义为“有且仅有一个元素的集合”。
单例模式最初的定义出现于《设计模式》(艾迪生维斯理, 1994):“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”
Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”

单例模式,可分为饿汉式单例模式和懒汉式单例模式。

好了,由于本人语言组织能力有限,还是直接上源码吧。(呵呵..)

package org.xjh.pattern;

/**
 * 单例模式
 * 
 * @author xjh
 * 
 */
public class SingletonTest {
	
	public static void main(String[] args) {
		//SingletonForHungryTest();
		SingletonForLazyTest();
	}
	
	public static void SingletonForLazyTest(){
		//创建两个饿汉式实例
		SingletonForLazy sfl1 = SingletonForLazy.newInstance();
		SingletonForLazy sfl2 = SingletonForLazy.newInstance();
		
		//单线程获取懒汉式实例
		System.out.println(sfl1.hashCode() == sfl2.hashCode());
		
		//多线程获取懒汉式实例
		for(int i = 0; i < 20; i++){
			new Thread(new Runnable(){
				@Override
				public void run() {
					System.out.println(SingletonForLazy.newInstance().hashCode());
				}
			}).start();
		}
	}
	
	public static void SingletonForHungryTest(){
		//创建两个饿汉式实例
		SingletonForHungry sfh1 = SingletonForHungry.newInstance();
		SingletonForHungry sfh2 = SingletonForHungry.newInstance();
		
		//单线程获取饿汉式实例
		System.out.println(sfh1.hashCode() == sfh2.hashCode());
		
		//多线程获取饿汉式实例
		for(int i = 0; i < 20; i++){
			new Thread(new Runnable(){
				@Override
				public void run() {
					System.out.println(SingletonForHungry.newInstance().hashCode());
				}
			}).start();
		}
	}
	
}

/**
 * 单例模式的饿汉式
 * @author xjh
 *
 */
class SingletonForHungry{
	/**
	 * 第3步:提供一个私有的静态的本类的实例变量
	 */
	private final static SingletonForHungry instance = new SingletonForHungry();
	/**
	 * 第1步:私有化构造方法
	 */
	private SingletonForHungry(){}
	
	/**
	 * 第2步:提供一个静态的获取该类实例的一个方法供外界使用
	 * @return
	 */
	public static SingletonForHungry newInstance(){
		return instance;
	}
}

/**
 * 单例模式的懒汉式
 * @author xjh
 *
 */
class SingletonForLazy{
	private static SingletonForLazy instance = null;
	
	private SingletonForLazy(){}
	
	public static SingletonForLazy newInstance(){
		
		//外部这层判断是为了提高性能,毕竟如果直接执行下面的代码的话,加锁和解锁是耗性能的
		if(instance == null){ 
			
			//加入同步锁,解决多线程访问带来的安全问题
			synchronized(SingletonForLazy.class){
				
				if(instance == null){ //判断是否已经实例化过了
					
					instance = new SingletonForLazy();
				}
			}
		}
		
		return instance;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值