小编jan*_*ano的帖子

具有多个参数的对象的工厂方法

让我介绍一下我的问题。我正在创建一组通常是食物的对象,但每个对象可能都有完全不同的一组属性需要设置。我想使用工厂设计模式,然后我遇到了在哪里以及如何设置对象属性的问题,然后我找到了一些构建器模式。但是我不确定我是否走在正确的道路上。例子:

class Food(object):
    def __init__(self, taste = None):
        self._taste = taste
class Bread(Food):
   def __init__(self, flour_type = None):
       Food.__init__(self, taste = 'good')
       self._flour = flour_type
class Meat(Food):
   def __init__(self, type = None, energy_value = None, taste = None):
       Food.__init__(self, taste = taste)
       self._type = type
       self._energy = energy_value
class Soup(Food):
   def __init__(self, name = None, recipe = None):
       Food.__init__(self, taste = 'fine')
       self._name = name
       self._recipe = recipe
Run Code Online (Sandbox Code Playgroud)

然后我有一个像这样的工厂:

FOOD_TYPES = {'food':Food, 'bread':Bread, 'meat':Meat, 'soup':Soup}

class FoodFactory(object):
    @staticmethod
    def create_food(food_type): …
Run Code Online (Sandbox Code Playgroud)

python oop design-patterns

5
推荐指数
1
解决办法
6725
查看次数

标签 统计

design-patterns ×1

oop ×1

python ×1