工厂方法分为模块

时间:2018-05-20 14:21:24

标签: design-patterns python-3.6 factory-pattern

我一直在看简单的工厂示例,

from __future__ import generators
import random

class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

并试图将其分解为单独的文件。

main.py

from __future__ import generators
import random

from factory.shapes.circle import Circle
from factory.shapes.sqaure import Square


class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)


# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

circle.py

from __future__ import generators
import random

from factory.main import Shape

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

square.py

from __future__ import generators
import random

from factory.main import Shape

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

运行时我得到了 ImportError:无法导入名称'Circle'

因此,虽然该示例在所有类都在同一模块中时起作用,但从分离的模块导入它们时似乎存在问题。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我刚刚将工厂类(Shape)从其他形状继承的Base类中分离出来,似乎可以解决这个问题