Skip to content

Commit 28cfa92

Browse files
committedJan 13, 2020
no message
1 parent 1f6426d commit 28cfa92

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
 

‎tests/单例模式使用不当.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author : ydf
3+
# @Time : 2020/1/13 0013 12:09
4+
"""
5+
错误使用设计模式的例子
6+
7+
"""
8+
from redis import Redis
9+
class MyRedis:
10+
_inst = None
11+
12+
def __new__(cls, *args, **kwargs):
13+
if not cls._inst:
14+
self = super().__new__(cls)
15+
self.__my_init__(*args, **kwargs)
16+
cls._inst = self
17+
return cls._inst
18+
19+
20+
def __my_init__(self,redis_db):
21+
print(f'传入的redis db是 {redis_db}')
22+
self.r = Redis(host='127.0.0.1',port=6379,db=redis_db)
23+
24+
def set(self,key,value):
25+
self.r.set(key,value)
26+
27+
if __name__ == '__main__':
28+
"""
29+
单例模式使用不当,造成项目巨大漏洞,同事说怎么没看到redis生成相关的,因为单例模式一直在db5,同事以为能放到db6,db7,应该使用享元模式,但错误的使用了单例模式。
30+
"""
31+
MyRedis(5).set('a',1)
32+
MyRedis(6).set('b', 2)
33+
MyRedis(5).set('c', 3)
34+
MyRedis(6).set('d', 4)
35+

‎创建型模式-享元模式.py

+38
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,45 @@
77
88
享元模式介于单例模式和不加控制得多例模式之间。非常灵活,实用性和使用场景大于单例模式。
99
例如创建一个数据库连接,不希望建立多个连接,但又要在同一解释器下操作好多台机器的数据库,当传参的机器的ip端口不同时候,那肯定要创建一个新的连接了,这种使用享元模式适合。
10+
11+
12+
例如原理有个同事写的代码是
13+
# -*- coding: utf-8 -*-
14+
# @Author : ydf
15+
# @Time : 2020/1/13 0013 12:09
1016
"""
17+
# 错误使用单例设计模式的例子
18+
19+
'''
20+
from redis import Redis
21+
class MyRedis:
22+
_inst = None
23+
24+
def __new__(cls, *args, **kwargs):
25+
if not cls._inst:
26+
self = super().__new__(cls)
27+
self.__my_init__(*args, **kwargs)
28+
cls._inst = self
29+
return cls._inst
30+
31+
32+
def __my_init__(self,redis_db):
33+
print(f'传入的redis db是 {redis_db}')
34+
self.r = Redis(host='127.0.0.1',port=6379,db=redis_db)
35+
36+
def set(self,key,value):
37+
self.r.set(key,value)
38+
39+
if __name__ == '__main__':
40+
"""
41+
单例模式使用不当,造成项目巨大漏洞,同事说怎么没看到redis生成相关的,因为单例模式一直在db5,同事以为能放到db6,db7,应该使用享元模式,单错误的使用了单例模式。
42+
"""
43+
MyRedis(5).set('a',1)
44+
MyRedis(6).set('b', 2)
45+
MyRedis(5).set('c', 3)
46+
MyRedis(6).set('d', 4)
47+
48+
'''
1149
from monkey_print2 import print
1250

1351

0 commit comments

Comments
 (0)
Please sign in to comment.