#!/usr/bin/env python
#coding=utf-8
#
# 工厂模式一例
# 版权所有 2014 yao_yu (http://blog.csdn.net/yao_yu_126)
# 本代码以MIT许可协议发布
# 2014-04-22
# class Cube(object):
pass class Cuboid(object):
pass class Cylinder(object):
pass class Sphere(object):
pass class ObjectFactory(dict):
def register(self, klass):
klass_name = klass.__name__
if klass_name not in self:
self[klass_name] = klass
def create(self, klass_name):
if klass_name in self:
return self[klass_name] object_factory = ObjectFactory()
for klass in (Cube, Cuboid, Cylinder, Sphere):
object_factory.register(klass) if __name__ == '__main__':
def main():
for klass in (Cube, Cuboid, Cylinder, Sphere):
obj = object_factory.create(klass.__name__)()
print(obj.__class__.__name__) main()
输出结果
Cube
Cuboid
Cylinder
Sphere