- 工厂模式实现了对多个类的统一管理,简单的理解就是判断应该调用哪个类
https://blog.csdn.net/qq_38934189/article/details/109112647
# 工厂模式
'''
一般情况下我们要创建一个工厂类(创造我们想创造的东西)
'''
class CarFactory: # 工厂类
def create_car(self, brand):
if brand == "奔驰":
return Benz()
elif brand == "宝马":
return BMW()
elif brand == "比亚迪":
return BYD()
else:
return '未知品牌,无法创建'
class Benz:
pass
class BMW:
pass
class BYD:
pass
factory = CarFactory()
c1 = factory.create_car("奔驰")
c2 = factory.create_car("宝马")
- 单例模式实现了,最资源的重复利用,比如数据库的连接.
https://blog.csdn.net/zm429438709/article/details/82048864
import pymysql
class Singleton(object):
_instance = None
def __new__(cls, name):
if not cls._instance:
cls._instance = object.__new__(cls)
return cls._instance
class A(Singleton):
def __init__(self, name):
self.name = name
self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
charset='utf8')
if __name__ == '__main__':
a = A('apple')
b = A('bnana')
print(a, b)