`

易学设计模式九 单例模式(Singleton)

阅读更多
单例模式确保某一个类只有一个实例,并且自行实例化向整个系统提供这个实例




饿汉式
public class EagerSingleton {
	
	private static final EagerSingleton instance = new EagerSingleton();
	
	private EagerSingleton(){}
	
	public static EagerSingleton getInstance() {
		return instance;
	}
}


懒汉式
public class LazySingleton {
	
	private static LazySingleton instance = null;
	
	private LazySingleton() {}
	
	synchronized public static LazySingleton getInstance() {
		if(instance == null) {
			instance = new LazySingleton();
		}
		return instance;
	}

}


Java语言中的单例模式
Java的Runtime对象
public class CmdTest {
	public static void main(String[] args) throws IOException {	
		Process proc = Runtime.getRuntime().exec("notepad.exe");
	}
}
  • 大小: 36 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics