• Python | 单例模式


    单例模式:一种设计模式。即 控制一个类只能产生一个对象
    单例模式用途广泛,如 音乐视频等播放器,打印机等等

    单例模式的标准写法
    甚至 需要写单例的时候把 User类中的内容 粘贴过去
     1 class User:
     2 
     3     __instance = None
     4     def __new__(cls, *args, **kwargs):
     5         if cls.__instance is None:
     6             cls.__instance = super().__new__(cls)
     7         return cls.__instance
     8 
     9 
    10 u1 = User()
    11 u2 = User()
    12 print(id(u1))
    13 print(id(u2))

    案例:

    办公室的打印机

    要求:
    一台打印机服务于一个办公室中的所有人,完成他们的打印任务

    分析:
    创建三个类
    1.打印机:1)将要打印的任务添加到打印的任务队列中;2)完成打印操作
    2.经理:将要打印的任务添加到打印机中
    3.员工:将要打印的任务添加到打印机中
     1 class Printer:
     2     __instance = None
     3     __pr_list = []
     4     def __new__(cls, *args, **kwargs):
     5         if cls.__instance is None:
     6             cls.__instance = super().__new__(cls)
     7         return cls.__instance
     8 
     9     @staticmethod
    10     def add_task(pr_info):
    11         Printer.__pr_list.append(pr_info)
    12         # Printer.to_print()  # 错!每添加一次任务都会把之前列表中的内容都再打印一遍
    13 
    14     @staticmethod
    15     def to_print():
    16         print(Printer.__pr_list)
    17 
    18 
    19 class Manager:
    20     @staticmethod
    21     def use_printer(printer, info):
    22         printer.add_task(info)
    23 
    24 
    25 class Stuff:
    26     @staticmethod
    27     def use_printer(printer, info):
    28         printer.add_task(info)
    29 
    30 
    31 printer = Printer()
    32 
    33 manager = Manager()
    34 manager.use_printer(printer,"经理打印")
    35 
    36 stuff = Stuff()
    37 stuff.use_printer(printer,"员工打印")
    38 
    39 printer.to_print()
  • 相关阅读:
    PHP添加Redis模块及连接
    Redis高级应用
    Redis常用命令
    Redis的数据类型及操作
    Redis下载及安装部署
    NoSQL介绍
    8种Nosql数据库系统对比
    JQ插件
    libcurl一般用法
    密钥对加密原理
  • 原文地址:https://www.cnblogs.com/ykit/p/11280517.html
Copyright © 2020-2023  润新知