Easton's Blog Easton's Blog
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)

Easton Yang

爱生活😊爱学习
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)
  • Python

    • Python学习

    • 代码

      • aes案例
      • hashlib案例
      • log案例
      • sftp案例
      • 单例
        • 案例
      • zip压缩案例
    • 数据结构与算法

  • Django

  • 后端
  • Python
  • 代码
eastonyangxu
2023-09-04
目录

单例

# 案例

# import fcntl
import sys


def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]

    return inner


class Singleton(object):
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}

    def __call__(self, *args, **kwargs):
        if self._cls not in self._instance:
            self._instance[self._cls] = self._cls(*args, **kwargs)
        return self._instance[self._cls]


class ClassSingle(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(ClassSingle, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


# class ScriptSingle:
#     pid_file = 0
#     is_run = False
#
#     def __init__(self, filepath):
#         self.pid_file = open(filepath, "w")
#
#         try:
#             fcntl.flock(self.pid_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
#         except BaseException:
#             self.is_run = True
#
#     def is_running(self):
#         return self.is_run


if __name__ == '__main__':
    @singleton
    class A:
        pass


    a, a1 = A(), A()
    print(id(a) == id(a1))


    @Singleton
    class B:
        pass


    b, b1 = B(), B()
    print(id(b) == id(b1))


    class C(metaclass=ClassSingle):
        pass


    c, c1 = C(), C()
    print(id(c) == id(c1))

    # s = ScriptSingle('single.pid')
    # if s.is_running():
    #     print('is running!')
    #     sys.exit(0)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#Python
上次更新: 2023/09/04, 18:39:45
sftp案例
zip压缩案例

← sftp案例 zip压缩案例→

最近更新
01
攻略制作要点
07-18
02
摄影主题拍摄
07-18
03
延时摄影剧本
07-18
更多文章>
Theme by Vdoing | Copyright © 2023-2024 Easton Yang | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式