沒有那么多的廢話直接上代碼
java 使用enum 實現單例模式,該種方法要求jd>=1.5的版本
public interface Country{
.................
}
public class China implements Country{
.................
/**
*
*獲取單例對象
*/
public static Country getInstance(){
return China.Singleton.INSTANCE.getInstance();
}
private enum Singleton{
INSTANCE;
private China singleton;
//JVM會保證此方法絕對只調用一次
Singleton(){
singleton = new China ();
}
public China getInstance(){
return singleton;
}
}
}
java 使用餓漢模式實現單例模式
public class China{
private static China instance = new China();
private China(){}
public static Singleton getInstance() {
return instance;
}
}
python 實現單例模式
# -*- coding: utf-8 -*-
# python 從模塊引入就是實現了單例模式
# 通過鎖實現 主要是在初始化方法中有I/O操作就可能造成單例模式的失敗
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
Singleton._instance = object.__new__(cls)
return Singleton._instance