1 #!/usr/bin/env python 2 #coding=utf-8 3 # 4 # 工厂模式一例 5 # 版权所有 2014 yao_yu (http://blog.csdn.net/yao_yu_126) 6 # 本代码以MIT许可协议发布 7 # 2014-04-22 8 # 9 10 class Cube(object): 11 pass 12 13 class Cuboid(object): 14 pass 15 16 class Cylinder(object): 17 pass 18 19 class Sphere(object): 20 pass 21 22 class ObjectFactory(dict): 23 def register(self, klass): 24 klass_name = klass.__name__ 25 if klass_name not in self: 26 self[klass_name] = klass 27 def create(self, klass_name): 28 if klass_name in self: 29 return self[klass_name] 30 31 object_factory = ObjectFactory() 32 for klass in (Cube, Cuboid, Cylinder, Sphere): 33 object_factory.register(klass) 34 35 if __name__ == '__main__': 36 def main(): 37 for klass in (Cube, Cuboid, Cylinder, Sphere): 38 obj = object_factory.create(klass.__name__)() 39 print(obj.__class__.__name__) 40 41 main() 42
输出结果
Cube
Cuboid
Cylinder
Sphere