345449.vhj5l3oj7.asia ShapeFactory2.py 2001-12-26T16:00:00Z 2001-12-26T16:00:00Z <br/><TEXTAREA name="code" class="py" rows="16" cols="100">#: c05:shapefact2:ShapeFactory2.py # Polymorphic factory methods. from __future__ import generators import random class ShapeFactory: factories = {} def addFactory(id, shapeFactory): ShapeFactory.factories.put[id] = shapeFactory addFactory = staticmethod(addFactory) # A Template Method: def createShape(id): if not ShapeFactory.factories.has_key(id): ShapeFactory.factories[id] = \ eval(id + '.Factory()') return ShapeFactory.factories[id].create() createShape = staticmethod(createShape) class Shape(object): pass class Circle(Shape): def draw(self): print &quot;Circle.draw&quot; def erase(self): print &quot;Circle.erase&quot; class Factory: def create(self): return Circle() class Square(Shape): def draw(self): print &quot;Square.draw&quot; def erase(self): print &quot;Square.erase&quot; class Factory: def create(self): return Square() def shapeNameGen(n): types = Shape.__subclasses__() for i in range(n): yield random.choice(types).__name__ shapes = [ ShapeFactory.createShape(i) for i in shapeNameGen(7)] for shape in shapes: shape.draw() shape.erase() #:~</TEXTAREA><br><br/><script type="text/javascript"><!--google_ad_client = "pub-9426659565807829";google_ad_slot = "9359905831";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> 2001-12-26T16:00:00Z