创建型模式
单例模式 (懒汉式)
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建;该类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
class SingletonObject:
def __new__(cls):
if not hasattr(SingletonObject,"__instance"):
SingletonObject.__instance = super().__new__(cls) #object.__new__(cls)
return SingletonObject.__instance
'''
def __init(cls, *args, **kwargs):
pass
def say(self):
print('hello')
'''
工厂模式
在创建对象时不对客户端暴露创建逻辑,并且通过使用一个共同的接口来指向新创建的对象(根据参数的取值来创建不同的实例)。
class Rectangle:
def draw(self):
print("Draw Rectangle")
class Square:
def draw(self):
print("Draw Square")
class Circle:
def draw(self):
print("Draw Circle")
class ShapeFactory:
shape = {'Rectangle':Rectangle, 'Square':Square, 'Circle':Circle}
def __new__(cls, shape_type):
if shape_type in cls.shape:
return cls.shape[shape_type]()
Reference
Static variables and methods in Python
Java单例模式的不同写法(编译期构建 / lazy initialization / double-checked locking / thread-safe / synchronized / volatile) [video] [video: Java内存模型]