单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。
Java实现
1>懒汉式(使用时判断,存在线程安全问题)
public class Singleton
{
private static Singleton instance;
private static String name;
private Singleton()
{
this.name = "lanhan";
System.out.println("I am Singleton of " + this.name);
}
public static Singleton getInstance()
{
if(instance == null)
{
instance = new Singleton();
return instance;
}
return instance;
}
}
2>饿汉式(加载类的时候生成一个实例)
public class SingletonE
{
//定义一个类变量,缓存实例
private static SingletonE instance = new SingletonE();
private static String name;
private SingletonE()
{
this.name = "ehan";
System.out.println("I am Singleton of " + this.name);
}
//保证只有一个实例
public static SingletonE getInstance()
{
return instance;
}
}
3>双重锁(解决懒汉式线程安全)
public class SingletonD
{
//定义一个类变量,缓存实例
private static SingletonD instance;
private static String name;
private SingletonD()
{
this.name = "double";
System.out.println("I am SingletonD of " + this.name);
}
//保证只有一个实例
public static SingletonD getInstance()
{
if(instance == null)
{
synchronized(SingletonD.class)
{
if(instance == null)
{
instance = new SingletonD();
}
}
}
return instance;
}
}
Python实现
1.普通实现
class Signleton(object):
"""docstring for Signleton"""
__instance = None
def __new__(cls, *args, **keywords):
# if not hasattr(cls, '__instance'):
if cls.__instance is None:
# if not cls.__instance:
cls.__instance = super(Signleton, cls).__new__(cls, *args, **keywords)
print cls.__instance
return cls.__instance
if __name__ == '__main__':
A = Signleton()
B = Signleton()
assert id(A) == id(B)
print A == B
2.装饰器实现
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x = 0):
self.x = x