jeudi 10 mars 2016

Factory method for objects with many parameters

Let me introduce my problem. I am creating a set of objects which are generally Food, but each of them might have completely different set of attributes to set. I thought to use Factory design pattern, then i faced a problem where and how to set objects attributes and then i found some Builder pattern. However i am not sure if i am at the right path. Example:

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

and then i have a factory like this:

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

class FoodFactory(object):
    @staticmethod
    def create_food(food_type):
        try:
            return FOOD_TYPES[food_type.lower()]()
        except Exception:
            return None

My question is: I want to pass parameters for constructors but dont know how. Is Builder pattern good idea here or not? The list of attributes might be longer. I was also wondering if passing a context dictionary with attribute name as a key and value as value. Any ideas how to solve this? Really appreciate any hints and tips.

Regards

Aucun commentaire:

Enregistrer un commentaire