登記式單態類
登記式單態類是GoF為了克服餓漢式單態類及懶漢式式單態類均不可繼承的缺點而設計的
圖
圖中的關系線表明
package com
import java
public class RegSingleton {
protected RegSingleton() {}
static public RegSingleton getInstance(String name)
{
if (name == null)
{
name =
}
if (m_registry
{
try
{
m_registry
}
catch(Exception e)
{
System
}
}
return (RegSingleton) (m_registry
}
static private HashMap m_registry = new HashMap();
static
{
RegSingleton x = new RegSingleton();
m_registry
}
public String about()
{
return
}
}
代碼清單
它的子類
圖
圖中的關系線表明
package com
import java
public class RegSingletonChild extends RegSingleton
{
public RegSingletonChild() {}
static public RegSingletonChild getInstance()
{
return (RegSingletonChild) RegSingleton
}
public String about()
{
return
}
}
代碼清單
在GoF原始的例子中
由於子類必須充許父類以構造子調用產生實例
GoF曾指出
爪哇語言裡的垃圾回收
爪哇語言裡垃圾回收使得單態類的使用變得有點復雜
在JDK
在JDK
在
圖
package com
import java
/**
* This class keeps your objects from garbage collected
*/
public class ObjectKeeper extends Thread {
private ObjectKeeper()
{
new Thread(this)
}
public void run()
{
try { join(); }
catch (InterruptedException e) {}
}
/**
* Any object passed here will be kept until you call discardObject()
*/
public static void keepObject(Object myObject)
{
System
m_keptObjects
System
}
/**
* This method will remove the protect of the object you pass in and make it
* available for Garbage Collector to collect
*/
public static void discardObject(Object myObject)
{
System
m_keptObjects
System
}
private static ObjectKeeper m_keeper = new ObjectKeeper();
private static Vector m_keptObjects = new Vector();
}
代碼清單
看守類應當自我實例化
一個實用的例子
這裡作者給出一個讀取屬性(properties)文件的單態類
圖
顯然
em
em
em
em
em
代碼清單
本例子的源代碼如下
package com
import java
import java
import java
public class ConfigManager
{
/**
* 私有的構造子
*/
private ConfigManager()
{
m_file = new File(PFILE);
m_lastModifiedTime = m_file
if(m_lastModifiedTime ==
{
System
}
m_props = new Properties();
try
{
m_props
}
catch(Exception e)
{
e
}
}
/**
*
* @return 返還ConfigManager類的單一實例
*/
synchronized public static ConfigManager getInstance()
{
return m_instance;
}
/**
* 讀取一特定的屬性項
*
* @param name 屬性項的項名
* @param defaultVal 屬性項的缺省值
* @return 屬性項的值(如此項存在)
*/
final public Object getConfigItem(String name
{
long newTime = m_file
// 檢查屬性文件是否被其它程序(多數情況是程序員手動)修改過
// 如果是
if(newTime ==
{
// 屬性文件不存在
if(m_lastModifiedTime ==
{
System
}
else
{
System
}
return defaultVal;
}
else if(newTime > m_lastModifiedTime)
{
m_props
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27517.html