單例模式(Singleton)
可分為eager模式
Java代碼
class EagerSingleton{
private static final EagerSingleton m_instance = new EagerSingleton()
private EagerSingleton(){}
public static EagerSingleton getInstance(){
return m_instance;
}
}
和 lazy模式
Java代碼
class LazySingleton{
private static LazySingleton m_instance = null;
private LazySingleton(){}
public synchronized static getInstance(){
if(m_instance == null){
m_instance = new LazySingleton()
}
return m_instance;
}
}
java源碼中
單例模式的精神就是整個系統中維護一個實例
多例模式(Multiton)
示例代碼如下
Java代碼
class Multiton{
private final int INSTANCE_SIZE =
private static Map instances = new HashMap(INSTANCE_SIZE)
private String name;
private Multiton(){}
private Multiton(String name){
this
}
public synchronized static getInstance(String name){
if(ntainsKey(name)){
return instances
}
else{
ins = new Multiton(name)
instances
return ins;
}
}
}
[nextpage]
一個實用的例子就是KeyGenerator
Java代碼
class KeyGenerator{
private final int POOL_SIZE =
private static Map instances = new HashMap(
private KeyInfo keyinfo;
private KeyGenerator(){}
private KeyGenerator(String keyName){
this
}
public synchronized static getInstance(String keyName){
if(ntainsKey(keyName)){
return (KeyGenerator)instances
}
else{
keyGen = new KeyGenerator(keyName)
instances
return keyGen;
}
}
public synzhronized int getNextKey(){
return keyinfo
}
}
其實
無論是用單例模式還是多例模式
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25909.html