⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shapefactory2.py

📁 this is the most basic to learn python
💻 PY
字号:
#: 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 "Circle.draw" 
  def erase(self): print "Circle.erase"
  class Factory:
    def create(self): return Circle() 

class Square(Shape):
  def draw(self): 
    print "Square.draw" 
  def erase(self): 
    print "Square.erase" 
  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()
#<hr>
output = '''
Square.draw
Square.erase
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
'''

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -