抽象原廠模式:提供一個建立一系列相關或相互依賴對象的介面,而無需指定它們具體的類。
優點:易於交換“產品系列”,只要更改相應的工廠即可。
缺點:建立產品的時候很繁瑣,需要增加和修改很多東西。
最佳化1:為了避免用戶端有過多的邏輯判斷,可以封裝出一個簡單工廠類來產生產品類。
最佳化2:為了減少簡單工廠類裡面的邏輯判斷,可以採用“反射”機制,直接根據外部的設定檔讀取出需要使用產品類的資訊。
#encoding=utf-8##by panda#抽象原廠模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk') #抽象產品A:user表class IUser(): def Insert(self): pass def GetUser(self): pass#sqlserver實現的Userclass SqlserverUser(IUser): def Insert(self): printInfo("在SQL Server中給User表增加一條記錄") def GetUser(self): printInfo("在SQL Server中得到User表的一條記錄")#Access實現的Userclass AccessUser(IUser): def Insert(self): printInfo("在Access中給User表增加一條記錄") def GetUser(self): printInfo("在Access中得到User表一條記錄")#抽象產品B:部門表class IDepartment(): def Insert(self): pass def GetUser(self): pass#sqlserver實現的Departmentclass SqlserverDepartment(IUser): def Insert(self): printInfo("在SQL Server中給Department表增加一條記錄") def GetUser(self): printInfo("在SQL Server中得到Department表的一條記錄")#Access實現的Departmentclass AccessDepartment(IUser): def Insert(self): printInfo("在Access中給Department表增加一條記錄") def GetUser(self): printInfo("在Access中得到Department表一條記錄")#抽象工廠class IFactory(): def CreateUser(self): pass def CreateDepartment(self): pass #sql server工廠class SqlServerFactory(IFactory): def CreateUser(self): return SqlserverUser() def CreateDepartment(self): return SqlserverDepartment()#access工廠class AccessFactory(IFactory): def CreateUser(self): return AccessUser() def CreateDepartment(self): return AccessDepartment() #最佳化一:採用一個簡單工廠類,封裝邏輯判斷操作class DataAccess():# db = "Sqlserver" db = "Access" @staticmethod def CreateUser(): if (DataAccess.db == "Sqlserver"): return SqlserverUser() elif(DataAccess.db == "Access"): return AccessUser() @staticmethod def CreateDepartment(): if (DataAccess.db == "Sqlserver"): return SqlserverDepartment() elif(DataAccess.db == "Access"): return AccessDepartment() #最佳化二:採用反射機制,避免使用太多判斷##以下資訊可以從設定檔中擷取DBType = 'Sqlserver' #'Access'DBTab_User = 'User'DBTab_Department = 'Department'class DataAccessPro():# db = "Sqlserver" db = "Access" @staticmethod def CreateUser(): funName = DBType + DBTab_User return eval(funName)() #eval 將其中的字串轉化為python運算式 @staticmethod def CreateDepartment(): funName = DBType + DBTab_Department return eval(funName)() def clientUI(): printInfo("\n--------抽象Factory 方法--------") factory = SqlServerFactory() iu = factory.CreateUser() iu.Insert() iu.GetUser() id = factory.CreateDepartment() id.Insert() id.GetUser() printInfo("\n--抽象Factory 方法+簡單Factory 方法--") iu = DataAccess.CreateUser() iu.Insert() iu.GetUser() id = DataAccess.CreateDepartment() id.Insert() id.GetUser() printInfo("\n-抽象Factory 方法+簡單Factory 方法+反射-") iu = DataAccessPro.CreateUser() iu.Insert() iu.GetUser() id = DataAccessPro.CreateDepartment() id.Insert() id.GetUser() returnif __name__ == '__main__': clientUI();
類圖: