I’m creating a pizza place application where employees will be able to create orders for customers(pizza and any number of toppings). This is for a school project but the requirements have nothing to do with this question.
On the GUI I have a number of checkboxes that the employee will use to determine which toppings the pizza should have. I want to use the decorator pattern for this.
This is what I want to do(just not sure if its a good idea):
I want to put all of my decorators in a separate namespace, and then using reflection grab all of the decorator names out of that name space and use them to build the checkbox list. The reason for doing this is because if more toppings are added later I think it would be beneficial to just be able to add assemblies (topping decorators) without having to recompile/re-distribute the entire application.
Thoughts?
(I just learned reflection and I have a hammer and am just trying to pound everything in that even remotely looks lilke a nail)
It’s not a bad approach in general – if there’s some common interface like “IPizzaTopping” and your new assemblies contain items of that interface then you can pull out all of the things in an assembly with that type.
Saying that, it’s complete overkill for something like pizza toppings (where an xml config could probably suffice) but I have seen it used to great effect with plugin type architectures.
1
The question is not so much whether or not you should use reflection to build the list of checkboxes from the set of subclasses you have defined. Once you have made that choice, and want to keep the GUI up-to-date without recompiling or maintaining the possible toppings in two different places (always a bad sign), there is little else you can do to enumerate classes (it would be different if you were enumerating instances of sibling classes, but I’m assuming there isn’t actually a persistent repository of Cheese, Tomato or Onion objects over which you could iterate).
The question should rather be: is representing toppings as classes the right idea, or is it overkill? As long as the only thing characteristic of a topping is what it makes the decorated pizza looks like, they could very well be parametrized instances of the same class. Having multiple subclasses is usually a good idea when one ore more behaviours systematically differ between them. For instance, the frameworks on which environments like Eclipse or NetBeans are built allow contributors to write extremely powerful plug-ins that nevertheless integrate into an existing installation, which involves implementing dozens of different behaviours. Not surprisingly, the frameworks themselves are heavily dependent on reflection to achieve the amazing flexibility they offer. But your problem, I think, is not so much a case of over-eager reflection than a case of over-eager inheritance.
2