I am creating a Menu application for a Coffee shop which has 4 different flavors of Coffee.
1. Black Coffe
2. Cappuccino
3. Mocha
4. Iced Coffe.
I have used factory method to generate these objects.
+ (Coffee *) getInstance:(COFFE_TYPE /*Enumeration*/):type{
Coffee *returnValue = nil;
switch(type){
case Black: returnValue = new Black_Coffee();
break;
case Cappuccino: returnValue = new Cap_Coffee();
break;
case Mocha: returnValue = new Mocha_Coffee();
break;
case Iced: returnValue = new Iced_Coffee();
break;
}
return returnValue;
}
In my Client I have to maintain a List of all available Coffee . I believe there is no way to get to know the subclasses for a given base class so I have to manually iterate over all my subclasses and use factory method for creation of each Object . This will become messy once I have 50 different types of coffee (which I will). So every time I add a new type I have to add it into the factory as well my client need to which additional item is added .
Is there a way so that I can transfer this entire logic at one place . So that just factory method would only know about the additional items and my client can call getAllItems on factory class itself and iterate over them or I should let my client handle the collection of items (which is the case right now).
The way I would handle this is create a static NSMutableDictionary, and when your app starts up, you can register the known coffee types using a new class method. The class method will do a setObject:forKey on the dictionary. Provide some means for the client to register as many objects as he wants, knowing that each “key” (name) has to be unique. That said, he could even overwrite the initial items you create by using the same key (and replace what ever object it is that is associate with that type.
I would use names not numbers (as you have now), but if you want to stick with numbers that works as long as you use a NSNumber for the key in the dictionary.