单例模式是23种设计模式之一。属于创建者模式里面的。
单例模式其实可以分为懒汉模式和饿汉模式。应用也很广泛。其实在链接数据库的时候采用单例,可以大大降低资源开销。下面介绍2种
具体例子。
packagecom.fish;
publicclassSingletonTestOne {
privatestaticSingletonTestOnesingletonTestOne=null;
privateSingletonTestOne() {
}
publicstatic synchronizedSingletonTestOnegetInstance() {//静态加载线程同步
if(singletonTestOne==null) {
singletonTestOne=newSingletonTestOne();
}
returnsingletonTestOne;
}
}
这个是懒汉模式,顾名思义,加载时不能创建实例,速度快,取对象慢。构造私有,所以只能通过唯一的static方法访问。
packagecom.fish;
publicclassSingletonTestTwo {
privatestaticSingletonTestTwosingletonTestTwo=newSingletonTestTwo();
privateSingletonTestTwo() {
}
publicstaticSingletonTestTwo getIntance() {
returnsingletonTestTwo;
}
}
//这个是饿汉模式,在加载的时候直接实例化。这样以后调用取对象快,也不存在线程问题。
所谓的单例模式就是只能创建一个实例,可以节省内存开销。