單例模式
屬于創建型模式
一個類只能有一個實例,并且自行實例化,必須自行向其他對象提供這個實例
關鍵代碼實現:
public class DataCenter {
//static variable
private static DataCenter singleton = null;
//private constructor
private DataCenter () {
}
//static method, synchronized
public synchronized static DataCenter getInstance() {
if (singleton == null)
singleton = new DataCenter ();
return singleton;
}
( NS0-111 jn0-120 )
注意事項:
構造器不公開private
getInstance方法的關鍵字synchronized static
使用場合:
任何只需要一個實例的地方
配置信息類(負責配置文件的解析)
管理者類
控制類
門面類
代理類
屬于創建型模式
一個類只能有一個實例,并且自行實例化,必須自行向其他對象提供這個實例
關鍵代碼實現:
public class DataCenter {
//static variable
private static DataCenter singleton = null;
//private constructor
private DataCenter () {
}
//static method, synchronized
public synchronized static DataCenter getInstance() {
if (singleton == null)
singleton = new DataCenter ();
return singleton;
}
( NS0-111 jn0-120 )
注意事項:
構造器不公開private
getInstance方法的關鍵字synchronized static
使用場合:
任何只需要一個實例的地方
配置信息類(負責配置文件的解析)
管理者類
控制類
門面類
代理類