ITeye博客

单例模式

darezhong · 2011-10-18 00:16 · 技术 · 编程语言 · 单例模式 · Markdown

单例模式:保证一个类仅有一个实例,并提供一个访问她的全局访问点。

有懒汉式与饿汉式之分: 1.懒汉式: public class Singleton {

private static Singleton instance = null;

private Singleton() {
	
}

public static synchronized Singleton getInstance() {
	if(instance == null) {
                       synchronized(synchronized.class) {
                            if(instance == null) {
                                instance = new Singleton();
                            }
                       }
	}
	return instance;
}

}

2.饿汉式: public class Singleton {

private static Singleton instance = new Singleton();

private Singleton() {
	
}

public static Singleton getInstance() {
	return instance;
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。