1
0
Fork 0
design-patterns/python/singleton/main.py

43 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
实例
汤宝宝混穿到了泰拉世界,并成为了泰拉联邦的唯一统治者。人类只有一个帝皇!
"""
# 帝皇类
class Emperor(object):
__instance = None
__name = ""
def __new__(cls, name: str, announce: str):
if not cls.__instance:
cls.__instance = super(Emperor, cls).__new__(cls)
cls.__instance.__name = name
return cls.__instance
def __init__(self, name: str, announce: str) -> None:
print(announce)
@property
def name(self) -> str:
return self.__name
def main() -> None:
print("========= 单例模式 =========")
# 创建帝皇
emperor1 = Emperor("汤宝宝", "泰拉联邦的帝皇诞生了!")
print(f"帝皇的名字是:{emperor1.name}")
emperor2 = Emperor("王二狗", "泰拉联邦的帝皇又一次诞生了!")
print(f"帝皇的名字是:{emperor2.name}")
if emperor1 is emperor2:
print(f"泰拉只有一个帝皇:{emperor1.name}\n")
print("======= 单例模式结束 =======")
if __name__ == "__main__":
main()