首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

singleton完善写法

2012-10-09 
singleton完美写法package com.june.study.design_pattens.singleton/**?* 写一个完美的还真不容易,感谢

singleton完美写法

package com.june.study.design_pattens.singleton;

/**
?* 写一个完美的还真不容易,感谢良葛格老师!
?*
?* 1. 实例的private性质和static性质
?* 2. 构造器的private性
?* 3. 如果是lazy-init的话,需要注意线程安全性
?* 4. 看看线程安全性设计里,synchronized的位置;为什么判断两次instance==null呢!
?*
?* @author lijg fantaxy025025@126.com?
?* @date Feb 25, 2010 1:27:19 PM
?* @version V3.0
?*/
public class LazyThreadSafeSongleton {
???
??? private static LazyThreadSafeSongleton instance = null;
???
??? private LazyThreadSafeSongleton(){
??? ??? //nothing here
??? }
???
??? /** 既然synchronized可以,lock也可以哦! */
??? public static LazyThreadSafeSongleton getInstance(){
??? ??? if(instance == null){//one
??? ??? ??? synchronized (LazyThreadSafeSongleton.class) {//here!
??? ??? ??? ??? if (instance == null) {//two
??? ??? ??? ??? ??? instance = new LazyThreadSafeSongleton();
??? ??? ??? ??? }
??? ??? ??? }
??? ??? }
??? ???
??? ??? return instance;
??? }
???
}

?

package com.june.study.design_pattens.singleton;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LazyThreadSafeSingleton2 {
??? private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
???
??? private static LazyThreadSafeSingleton2 instance = null;
???
??? private LazyThreadSafeSingleton2(){
??? ??? //nothing here
??? }
???
??? /** 既然synchronized可以,lock也可以哦! */
??? public static LazyThreadSafeSingleton2 getInstance(){
??? ??? if(instance == null){//one
??? ??? ??? reentrantReadWriteLock.writeLock().lock();
??? ??? ??? try {
??? ??? ??? ??? if (instance == null) {
??? ??? ??? ??? ??? instance = new LazyThreadSafeSingleton2();
??? ??? ??? ??? }
??? ??? ??? } catch (Exception e) {
??? ??? ??? ??? //sth here
??? ??? ??? } finally{
??? ??? ??? ??? reentrantReadWriteLock.writeLock().unlock();
??? ??? ??? }
??? ??? }
??? ???
??? ??? return instance;
??? }
???
}

?

package com.june.study.design_pattens.singleton;

public class NormalSingleton {

??? private static NormalSingleton instance = new NormalSingleton();//here!
???
??? private NormalSingleton(){
??? ??? //nothing here
??? }
???
??? public static NormalSingleton getInstance(){
??? ??? return instance;
??? }
???
??? public static void main(String[] args) {
??? ???
??? }

}

?

?

热点排行