How to implement a factory class?(如何实现工厂类?)
                            本文介绍了如何实现工厂类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我希望能够基于枚举类创建对象,并使用字典。大概是这样的:
class IngredientType(Enum):
    SPAM        = auto() # Some spam
    BAKE_BEANS  = auto() # Baked beans
    EGG         = auto() # Fried egg
class Ingredient(object):
    pass    
class Spam(Ingredient):
    pass
class BakedBeans(Ingredient):
    pass
class Egg(Ingredient):
    pass
class IngredientFactory(object):
    """Factory makes ingredients"""
    choice = {
        IngredientType.SPAM: IngredientFactory.MakeSpam,
        IngredientType.BAKED_BEANS: IngredientFactory.MakeBakedBeans,
        IngredientType.EGG: IngredientFactory.MakeEgg
    }
    @staticmethod
    def make(type):
        method = choice[type]
        return method()
    @staticmethod
    def makeSpam():
        return Spam()
    @staticmethod
    def makeBakedBeans():
        return BakedBeans()
    @staticmethod
    def makeEgg():
        return Egg()
但我收到错误:
NameError: name 'IngredientFactory' is not defined
由于某种原因,无法创建词典。 我在哪里做错了?
推荐答案
查看Bruce Eckel's book后,我想到了这个:
#Based on Bruce Eckel's book Python 3 example
# A simple static factory method.
from __future__ import generators
import random
from enum import Enum, auto
class ShapeType(Enum):
    CIRCLE  = auto() # Some circles
    SQUARE  = auto() # some squares
class Shape(object):
    pass
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")
class ShapeFactory(object):
    @staticmethod
    def create(type):
        #return eval(type + "()") # simple alternative
        if type in ShapeFactory.choice:
            return ShapeFactory.choice[type]()
        assert 0, "Bad shape creation: " + type    
    choice = { ShapeType.CIRCLE:  Circle,
               ShapeType.SQUARE:  Square                
             }
# Test factory
# Generate shape name strings:
def shapeNameGen(n):
    types = list(ShapeType)
    for i in range(n):
        yield random.choice(types)
shapes = 
  [ ShapeFactory.create(i) for i in shapeNameGen(7)]
for shape in shapes:
    shape.draw()
    shape.erase()
这会让用户从枚举中选择类类型,并阻止任何其他类型。这也意味着用户不太可能写出拼写错误的"坏字符串"。他们只使用枚举。 然后,测试的输出如下所示:
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
Square.draw
Square.erase
Circle.draw
Circle.erase
Circle.draw
Circle.erase
Square.draw
Square.erase
这篇关于如何实现工厂类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:如何实现工厂类?
 
				
         
 
            
        基础教程推荐
             猜你喜欢
        
	     - 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				