饿汉式单例产生班长,模拟班会举行
时间: 2023-05-30 11:04:12 浏览: 175
class ClassPresident:
__instance = None # 类变量,用于存储唯一实例
def __init__(self, name):
self.name = name
@classmethod
def get_instance(cls, name):
if not cls.__instance:
cls.__instance = ClassPresident(name)
return cls.__instance
def call_meeting(self):
print(f"{self.name}主持班会,开始发言!")
def end_meeting(self):
print(f"{self.name}宣布本次班会结束。")
# 饿汉式单例模式
class_president = ClassPresident.get_instance("张三")
print(f"班长是{class_president.name}")
class_president.call_meeting()
class_president.end_meeting()
# 尝试创建另一个班长实例
class_president2 = ClassPresident.get_instance("李四")
print(f"班长是{class_president2.name}")
class_president2.call_meeting() # 与班长1相同
class_president2.end_meeting() # 与班长1相同
阅读全文