singleton模式保证在java程序中,一个class只有一个实例存在。并提供一个访问它的全局访问点。
在很多单线程的场合(建立目录、数据库连接)等。
由于sinngleton能够被状态化,如果多个单态class在一起就出现了状态工厂,向外部提供状态服务。
在遇到唯一数的问题(记录网站被访次数等),就可以用单态。并且能synchroinzed的安全的加1。
singleton也能够被无状态化,提供工具的性质。(还有点不理解,请高手meconsea@hotmail.com)
singleton 限制了实例个数,有利于gc的回收。
在工厂模式中类装入器(class loader)中也用singleton模式实现的。因为装入的class也属于资源。
一般singleton有两种模式:
first:
public class singletontest1 {
private singletontest1(){}
private static singletontest1 singletoninstance = new singletontest1();
public static singletontest1 newinstance(){
return singletoninstance;
}
}
second:
public class singletontest2 {
private singletest2(){}
private static singletontest2 newinstance = null;
public static synchronized singletontest2 newinstance(){
//比first更提高效率,因为实例只生成一次
if(newinstance == null){
newinstance = new singletest2();
}
return newinstance;
}
}
有时在某些情况下,使用singleton并不能达到singleton的目的,如有多个singleton对象同时被不同的类装入器装载;在ejb这样的分布式系统中使用也要注意这种情况,因为ejb是跨服务器,跨jvm的。
