单例模式实现一:
public class Test{
private static Test test = new Test();
private Test(){}
public static Test getInstance(){
return test;
}
}实现二:
public enum Test{
INSTANCE;
}就这么简单,你照着这样的公式套用不就行了,你贴那么多代码没必要
public class Test{
private static Test test = new Test();
private Test(){}
public static Test getInstance(){
return test;
}
}实现二:
public enum Test{
INSTANCE;
}就这么简单,你照着这样的公式套用不就行了,你贴那么多代码没必要
private static Test test = null;
private Test()
{
}
public static Test getInstance(){
if(test = null)
{
test = new Test();
}
return test;
}}
public class SingletonTest
{
public static void main(String[] args)
{
Singleton singleton = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton == singleton2);
}
}
class Singleton
{
private static Singleton singleton;
private Singleton()
{
} public static Singleton getInstance()
{
if(singleton == null)
{
singleton = new Singleton();
} return singleton;
}
}
单例模式:顾名思义,就是在类外只有一个该类的实例对象,如果一个类能够多次实例化,就无从谈起单例,所以单例模式首要解决的是new 的问题,在类外,不能使用new创建该类的实例对象,如果类不能实例化了,那么怎么获取对象呢?这就需要类提供一个静态获取固定对象的方法,切记,这个对象是固定的,也就是始终是一个对象。
应用:单例模式的对象一般是使用频度高,或者较为占用资源的类,将其单例化以提高时空的效率;
分类:单例模式,很多时候就是讲一个静态方法提供一个固定对象,但是另外一种常见的方式是与线程绑定的单例模式,一个线程绑定一个类的实例,常见于filter,session,connection中的数据连接处理,事务,或者其他需要与线程进行绑定的情形;
代码1:普通单例public class Singeleton2 {
private Singeleton2(){}//私有化构造,类外不能实例化
private static Singeleton2 singlelenton2;//固定的静态实例对象
public static synchronized Singeleton2 getInstance2(){//加锁保证线程安全,确保单例
return singlelenton2==null?(singlelenton2=new Singeleton2()):singlelenton2;
}
}
代码2:线程单例//线程单例模式,业务和性能双向考虑
public class ThreadSingleton2 {
private ThreadSingleton2(){}
private static ThreadLocal<ThreadSingleton2> tl=new ThreadLocal<ThreadSingleton2>();
public static ThreadSingleton2 getInstance(){
if(tl.get()==null)tl.set(new ThreadSingleton2());
return tl.get();
}
}
http://www.cnblogs.com/whgw/archive/2011/10/05/2199535.html