◎筱米加步枪◎.Blog

Happy coding

单例模式

筱米加步枪 posted @ 2010年3月09日 01:35 in [ 设计模式 ] with tags 设计模式 单例模式 , 1363 阅读

本想跳过单例模式的~~但是要有始有终~~果然,还好没跳过。。

以为单例模式就之前用的那样,没想到之前的存在一定的局限性和不安全性~~只是情况还没发生而已~~

摘自《head first》中~~总结如下:

第一种单例模式:

package com.shine.singleton1;

/**
 * 单例模式1
 * 优点:该种单例模式有延迟实例化,当需要使用该类的时候才被实例化
 *      提高了性能。
 * 缺点: 对于多线程处理会有Bug,可能有多个线程同时访问getInstance()方法
 * @author ChenST
 *
 * @create 2010-3-9
 */
public class Singleton {

	/** 改类本身的一个类变量 */
	private static Singleton instance;
	
	/**
	 * 私有构造函数,防止外部对这个类实例化
	 */
	private Singleton(){ }
	
	/**
	 * 返回该类的一个实例
	 * 这个方法保证instance只能被实例化一次.
	 * 而instance是类变量,当实例化后,被共享着
	 * @return
	 */
	public static Singleton getInstance(){
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}

第二种单例模式:

package com.shine.singleton2;

/**
 * 单例模式2
 * 优点:该种单例模式使用了同步机制,解决了多线程的同时访问
 * 缺点: 降低了性能
 * @author ChenST
 *
 * @create 2010-3-9
 */
public class Singleton {

	private static Singleton instance;
	
	private Singleton(){}
	
	/**
	 * 返回该类的一个实例(使用了同步机制)
	 * @return
	 */
	public static synchronized  Singleton getInstance(){
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}

第三种单例模式:

package com.shine.singleton3;

/**
 * 单例模式3(使用"切急"创建实例)
 * 优点:可保存线程安全
 * 缺点: 如果这个类比较大,而且很久未使用,造成资源的浪费。
 * @author ChenST
 *
 * @create 2010-3-9
 */
public class Singleton {

	/** 在静态初始化初始化该实例 可保证线程安全 */
	private static Singleton instance=new Singleton();
	
	private Singleton(){ }
	
	/**
	 * 返回该类的一个实例(已经有了实例,直接返回)
	 * @return
	 */
	public static Singleton getInstance(){
		return instance;
	}
}

第四种单例模式:

package com.shine.singleton4;

/**
 * 单例模式4(推荐)
 * 平衡了性能和安全
 * @author ChenST
 *
 * @create 2010-3-9
 */
public class Singleton {
 
	/** 保证多个线程的拷贝值和"主"存区域的值相同 */
	private volatile static Singleton instance;
	
	private Singleton(){ }
	
	/**
	 * 返回该类的一个实例
	 * @return
	 */
	public static  Singleton getInstance(){
		//如果不存在,则进入同步区块
		if(instance==null){   
			synchronized (Singleton.class) {
				//进入同步区块,再检查一次
				if(instance==null){
					instance=new Singleton();
				}
			}
			instance=new Singleton();
		}
		return instance;
	}
}

看具体情况使用咯~~~

pavzi.com 说:
2024年1月19日 05:56

The primary idea or goal of this website has been to offer resources that contain comprehensive information on every subject and are accessible via the Internet. making certain that each and every reader finds the most relevant and pavzi.com worthwhile information regarding the subject they are searching for and linking to our content.Because our website is multi-niche or multi-category, it will guarantee that it offers resources and information on every subject. Our website features a number of timeless topics, including career, job recruitment, education, technology, and reviews, among others. Indeed, Tech, Finance, and Product Reviews are our primary focus.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter