Skip to content

Commit 762b13a

Browse files
author
LAPTOP-7V78BBO2\ydf19
committedMar 7, 2025
Changes
1 parent a1e722f commit 762b13a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
相比这个文件, 创建型模式-享元模式.py
3+
4+
使 __init__ 只运行异常,阻止相同对象多次运行 __init__
5+
"""
6+
7+
import dataset
8+
9+
10+
class DatasetSink:
11+
# 类级别的实例缓存,按 db_url 存储
12+
_instances = {}
13+
_has__init_set =set() # 把执行了 __init__的对象id保存起来对比
14+
15+
def __new__(cls, db_url):
16+
# 如果 db_url 已存在,直接返回已有实例
17+
if db_url not in cls._instances:
18+
# 创建新实例并存入缓存
19+
self = super(DatasetSink, cls).__new__(cls)
20+
cls._instances[db_url] = self
21+
return cls._instances[db_url]
22+
23+
def __init__(self, db_url): # 相同的db_url不要每次都运行这个__init__。
24+
if id(self) not in self.__class__._has__init_set :
25+
print(f'创建连接 {db_url}')
26+
self.db = dataset.connect(db_url,ensure_schema=True)
27+
self.__class__._has__init_set.add(id(self))
28+
29+
def save(self, table_name:str,data:dict,):
30+
# 使用已有的连接插入数据
31+
table = self.db[table_name]
32+
table.insert(data)

0 commit comments

Comments
 (0)
Please sign in to comment.