1. 程式人生 > 實用技巧 >Python 工廠模式,單例模式簡單理解

Python 工廠模式,單例模式簡單理解

  1. 工廠模式實現了對多個類的統一管理,簡單的理解就是判斷應該呼叫哪個類

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("寶馬")
  1. 單例模式實現了,最資源的重複利用,比如資料庫的連線.

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)