-------------------------------------------------java 方式----------------------------------------------------------------------------------
package algurimProject;
public class SingleClass {
//懒汉模式,线程不安全
public static class Singleton{
private static Singleton singleton = null;
private Singleton() {
}
public static Singleton getSingleton() {
if(singleton ==null) {
singleton = new Singleton();
}
return singleton;
}
}
//饿汉模式,线程安全
public static class Singleton2{
private static Singleton2 singleton2 = new Singleton2();
private Singleton2() {
}
public static Singleton2 getSingleton2(){
return singleton2;
}
}
// 懒汉模式,线程安全模式
public static class Singleton3{
private static Singleton3 singleton3 = null;
private Singleton3() {
}
public static synchronized Singleton3 getSingleton3() {
if(singleton3 ==null) {
singleton3 = new Singleton3();
}
return singleton3;
}
}
/**
* 静态内部类,使用双重校验锁,线程安全【推荐】
*/
public static class Singleton4 {
private volatile static Singleton4 instance = null;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (instance == null) {
synchronized (Singleton4.class) {
if (instance == null) {
instance = new Singleton4();
}
}
}
return instance;
}
}
/**
* 单例模式,使用静态内部类,线程安全【推荐】
*/
public static class Singleton5 {
private final static class SingletonHolder {
private static final Singleton5 INSTANCE = new Singleton5();
}
private Singleton5() {
}
public static Singleton5 getInstance() {
return SingletonHolder.INSTANCE;
}
}
}
-------------------------------------------------python 方式----------------------------------------------------------------------------------
# 用__new__实现
class SingleClass(object):
__instance = None
__first_init = None
def __new__(cls, age, name):
if not cls.__instance:
SingleClass.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, age, name):
if not self.__first_init:
self.age = age
self.name = name
SingleClass.__first_init = True
a = SingleClass(21, "jatrix")
b = SingleClass(2, "jatrix")
print(id(a))
print(id(b))
print(a.age)
print(b.age)
a.age = 33
print(b.age)
# 使用注解的方式
def singleton(cls, *args, **kwargs):
instance = {}
def __singleton():
if cls not in instance:
instance[cls] = cls
return instance[cls]
return __singleton
@singleton
class MyClass:
kind = "type"
def __init__(self, name):
self.name = name
@singleton
class MyAnotherClass:
name = "another"
def __init__(self, age):
self.age = age
one = MyClass()
two = MyClass()
print(id(one))
print(id(two))
another_one = MyAnotherClass()
another_two = MyAnotherClass()
print(id(another_one))
print(id(another_two))