Python语言实现工厂方法设计模式

根据软件设计原则中开放封闭原则的指导思想, 一个类写好后,尽量不要修改里面的内容, 而是通过添加新的继承应对变化, 简单工厂不符合这个设计原则, 所以本篇文章将使用伪代码介绍工厂方法设计模式的使用

背景: 现公司监控系统报警需要对接企业微信公众号, 由于未认证企业微信推送消息的限制, 默认每天推送条数上限为6000条, 考虑到报警系统多, 规则没有收敛, 接收的人员多, 每天6000条可能不够用, 所以需要创建多个未认证的企业微信账号用于发送报警信息. 我们将以此需求为背景, 演示工厂方法的设计模式

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

class WeChat:

def send_message(self, content):
pass

def send_image(self, imageid):
pass


class AccountA(WeChat):

def send_message(self, content):
print("使用企业微信账号A推送信息: ", content)

def send_image(self, imageid):
print("使用企业微信账号A推送图片: ", imageid)


class AccountB(WeChat):

def send_message(self, content):
print("使用企业微信账号B推送信息: ", content)

def send_image(self, imageid):
print("使用企业微信账号B推送图片: ", imageid)


class WeChatFactory:

def create_wechat(self):
pass


class AccountAFactory(WeChatFactory):

def create_wechat(self):
return AccountA()


class AccountBFactory(WeChatFactory):

def create_wechat(self):
return AccountB()


if __name__ == "__main__":
# 实例化账号A
wechat_factory_a = AccountAFactory()
# 创建账号A的微信对象
wechat1 = wechat_factory_a.create_wechat()
wechat2 = wechat_factory_a.create_wechat()
wechat3 = wechat_factory_a.create_wechat()
# 使用账号A对象发送信息
wechat1.send_message(content="haha")
wechat2.send_message(content="hehe")
wechat3.send_message(content="xixi")

# 实例化账号B
wechat_factory_b = AccountBFactory()
# 创建账号B的微信对象
wechat4 = wechat_factory_b.create_wechat()
wechat5 = wechat_factory_b.create_wechat()
# 使用账号B对象发送信息
wechat4.send_message(content="heihei")
wechat5.send_message(content="pupu")

执行结果:

1
2
3
4
5
使用企业微信账号A推送信息:  haha
使用企业微信账号A推送信息: hehe
使用企业微信账号A推送信息: xixi
使用企业微信账号B推送信息: heihei
使用企业微信账号B推送信息: pupu

如果此时, 两个微信账号都不够用了, 需要增加第三个账号时, 所有的类都不需要修改, 只需创建新的类即可, 符合开放封闭原则

1
2
3
4
5
6
7
8
9
10
11
12
13
class AccountC(WeChat):

def send_message(self, content):
print("使用企业微信账号C推送信息: ", content)

def send_image(self, imageid):
print("使用企业微信账号C推送图片: ", imageid)


class AccountCFactory(WeChatFactory):

def create_wechat(self):
return AccountC()