现使用单例模式模拟该场景。皇帝
时间: 2024-05-18 22:06:58 浏览: 75
单例模式应用场景
class Emperor:
__instance = None
def __init__(self):
if Emperor.__instance is not None:
raise Exception("Cannot create more than one instance of Emperor")
else:
Emperor.__instance = self
@staticmethod
def get_instance():
if Emperor.__instance is None:
Emperor()
return Emperor.__instance
def say(self):
print("I am the only Emperor of this dynasty!")
emperor1 = Emperor.get_instance()
emperor1.say() # Output: "I am the only Emperor of this dynasty!"
emperor2 = Emperor.get_instance() # Raises an exception: "Cannot create more than one instance of Emperor"
阅读全文