单例模式

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css); 饱汉模式:

package com.jerry.design.singleton;


public class FullSingle {

private static FullSingle instance = null;

private FullSingle(){

}


public synchronized static FullSingle getIntance(){

if(instance==null){

instance = new FullSingle();

}

return instance

}

}


饿汉模式:


package com.jerry.design.singleton;


public class HungrySingle {

private static HungrySingle instance = new HungrySingle();

private HungrySingle(){

}


public static HungrySingle getIntance(){

return instance

}

}


测试代码:

package com.jerry.design.singleton;



public class Test {

public static void main(String[] args) {

for(int i=0;i<=10;i++){

System.out.println(FullSingle.getIntance());

System.out.println(HungrySingle.getIntance());

}

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf

// com.jerry.design.singleton.FullSingle@3487a5cc

// com.jerry.design.singleton.HungrySingle@eb42cbf


}


}



总结: 保持单jvm下的唯一实例。

 

posted on 2012-02-19 20:55 疯狂的蜗牛 阅读(72) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

公告

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

常用链接

留言簿

随笔档案

文章分类

文章档案

搜索

最新评论