单例模式

public class Singleton {

private Singleton(){

System.out.println("only one instance");

}

 

private static Singleton instance = null;

 

public static synchronized Singleton singleton(){ // thread safe

if(instance == null){

instance = new Singleton();

}

return instance;

}

 

}

 
单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。要点:
1. private 构造方法;
2. private static 成员变量;
3. public static 线程安全的成员变量实例化方法,并返回唯一的实例;
 
posted @ 2012-02-19 17:16  swucim  阅读(96)  评论(0)    收藏  举报