TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
程序中经常有这样的要求,整个程序运行时只有一个实例被使用。
比如:数据库连接池,系统参数配置,java API 中的 Runtime, Calendar ...
如何实现这种需求。
代码如下
public class ConnectionPoolManager {
private static instance = null;
private ConnectionPoolManager() {
// do some initialize work
}
public static void getInstance() {
if (instance == null){
instance = new ConnectionPoolManager();
}
return instance;
}
public Connection getConnection(){
}
}
ConnectionPoolManager 的使用
public class QueryFunctions {
public static Collection findStudentByName(String name){
ConnectPoolManager connectionPoolManager =ConnectionPoolManager.getInstance();
Connection conn = connectionPoolManager.getConnection();
// query database
}
}
1.instance 是私有的,开始时赋值为 null,外部只有通过 getInstance 方法才能获得他。
2.构造方法是私有的,这点很重要,保证只有这个类自己才能够调用,其他的类无法调用此构造函数。
3.getInstance 方法中:
if 语句,保证只有一个 instance 存在唯一的一个 ConnectionPoolManager 在第一次调用的时候被建立。
下面是另一个例子: java.lang.Runtime的实现如下:
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don‘t let anyone else instantiate this class */
// 够狠
private Runtime() {}
}
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
} |
|