Python設(shè)計模式之抽象工廠模式原理與用法詳解
本文實例講述了Python設(shè)計模式之抽象工廠模式原理與用法。分享給大家供大家參考,具體如下:
抽象工廠模式(Abstract Factory Pattern):提供一個創(chuàng)建一系列相關(guān)或相互依賴對象的接口,而無需指定它們的類
下面是一個抽象工廠的demo:
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Andy' """ 大話設(shè)計模式 設(shè)計模式——抽象工廠模式 抽象工廠模式(Abstract Factory Pattern):提供一個創(chuàng)建一系列相關(guān)或相互依賴對象的接口,而無需指定它們的類 """ import sys #抽象用戶表類 class User(object): def get_user(self): pass def insert_user(self): pass #抽象部門表類 class Department(object): def get_department(self): pass def insert_department(self): pass #操作具體User數(shù)據(jù)庫類-Mysql class MysqlUser(User): def get_user(self): print 'MysqlUser get User' def insert_user(self): print 'MysqlUser insert User' #操作具體Department數(shù)據(jù)庫類-Mysql class MysqlDepartment(Department): def get_department(self): print 'MysqlDepartment get department' def insert_department(self): print 'MysqlDepartment insert department' #操作具體User數(shù)據(jù)庫-Orcal class OrcaleUser(User): def get_user(self): print 'OrcalUser get User' def insert_user(self): print 'OrcalUser insert User' #操作具體Department數(shù)據(jù)庫類-Orcal class OrcaleDepartment(Department): def get_department(self): print 'OrcalDepartment get department' def insert_department(self): print 'OrcalDepartment insert department' #抽象工廠類 class AbstractFactory(object): def create_user(self): pass def create_department(self): pass class MysqlFactory(AbstractFactory): def create_user(self): return MysqlUser() def create_department(self): return MysqlDepartment() class OrcaleFactory(AbstractFactory): def create_user(self): return OrcaleUser() def create_department(self): return OrcaleDepartment() if __name__ == "__main__": db = sys.argv[1] myfactory = '' if db == 'Mysql': myfactory = MysqlFactory() elif db == 'Orcal': myfactory = OrcaleFactory() else: print "不支持的數(shù)據(jù)庫類型" exit(0) user = myfactory.create_user() department = myfactory.create_department() user.insert_user() user.get_user() department.insert_department() department.get_department()
上面類的設(shè)計如下圖:
優(yōu)點:
具體工廠類如MysqlFactory在一個應(yīng)用中只需要初始化一次,這樣改動一個具體工廠變得很容易,只需要改變具體工廠就可以改變整個產(chǎn)品的配置。
具體的創(chuàng)建實例過程與客戶端分離,客戶端通過他們的抽象接口操縱實例,產(chǎn)品的具體類名也被具體工廠的實現(xiàn)分離,不會出現(xiàn)在客戶端代碼中
缺點:在新增一個具體工廠就需要增加多個類才能實現(xiàn)
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python 實現(xiàn)勞拉游戲的實例代碼(四連環(huán)、重力四子棋)
這篇文章主要介紹了Python 實現(xiàn)勞拉游戲的實例代碼(四連環(huán)、重力四子棋),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Python中pandas的dataframe過濾數(shù)據(jù)方法
這篇文章主要介紹了Python中pandas的dataframe過濾數(shù)據(jù)方法,Pandas是另外一個用于處理高級數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析的Python庫,Pandas是基于Numpy構(gòu)建的一種工具,需要的朋友可以參考下2023-07-07