工厂方法模式

模式说明

工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法模式让实例化推迟到子类。

和简单工厂区别在于,每个工厂只管生产自己对应的产品,而简单工厂是一个工厂生产各种产品。

模式结构图

程序示例

说明:

一个日志类,两个派生类(文件日志和事件日志);一个日志工厂类(返回日志类),两个派生类(分别生产文件日志类和事件日志类)

代码:

 1 class log(object):
 2     def write(self):
 3         pass
 4 
 5 class eventLog(log):
 6     def write(self):
 7         print 'eventLog'
 8 
 9 class fileLog(log):
10     def write(self):
11         print 'fileLog'
12 
13 class logFactory(object):
14     def create(self):
15         return log()
16 
17 class eventLogFactory(logFactory):
18     def create(self):
19         return eventLog()
20 
21 class fileLogFactory(logFactory):
22     def create(self):
23         return fileLog()
24 
25 if __name__=='__main__':
26     factory = fileLogFactory()
27     log = factory.create()
28     log.write()
29 
30     factory = eventLogFactory()
31     log = factory.create()
32     log.write()

运行结果:

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

原文地址:https://www.cnblogs.com/cotton/p/3930706.html