本文实例讲述了python设计模式之抽象工厂模式原理与用法。分享给大家供大家参考,具体如下:
抽象工厂模式(abstract factory pattern):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类
下面是一个抽象工厂的demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'andy' """ 大话设计模式 设计模式——抽象工厂模式 抽象工厂模式(abstract factory pattern):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类 """ 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数据库类-mysql class mysqluser(user): def get_user( self ): print 'mysqluser get user' def insert_user( self ): print 'mysqluser insert user' #操作具体department数据库类-mysql class mysqldepartment(department): def get_department( self ): print 'mysqldepartment get department' def insert_department( self ): print 'mysqldepartment insert department' #操作具体user数据库-orcal class orcaleuser(user): def get_user( self ): print 'orcaluser get user' def insert_user( self ): print 'orcaluser insert user' #操作具体department数据库类-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 "不支持的数据库类型" exit( 0 ) user = myfactory.create_user() department = myfactory.create_department() user.insert_user() user.get_user() department.insert_department() department.get_department() |
上面类的设计如下图:
优点:
具体工厂类如mysqlfactory在一个应用中只需要初始化一次,这样改动一个具体工厂变得很容易,只需要改变具体工厂就可以改变整个产品的配置。
具体的创建实例过程与客户端分离,客户端通过他们的抽象接口操纵实例,产品的具体类名也被具体工厂的实现分离,不会出现在客户端代码中
缺点:在新增一个具体工厂就需要增加多个类才能实现
希望本文所述对大家python程序设计有所帮助。
原文链接:https://www.cnblogs.com/onepiece-andy/p/python-abstract-factory-pattern.html