views:

41

answers:

1

Right now, I've got a switch statement which is being used to create objects based on a string. There are three types of objects which extend an abstract generic object. I should really be using a factory pattern, which I'm figuring out right now. My issue is thus: I appreciate the flexibility of the factory pattern, but right now I'm storing the would-be products in special dictionaries dedicated to their type.

_type1[location] = ArrayOfType1s
_type2[location] = ArrayOfType2s
_type3[location] = ArrayOfType3s

That works if I only have three types, but if I decide to add more with the flexibility of the factory pattern, then that presents the problem of how to store them, as I'd have to make a special dictionary each time I add one...

The only answer that I can think of is to nest my dictionaries, which sounds pretty slow.

_factoryOutput[type] = type[location] = ArrayOfTypes

That's probably a workable solution, but can anyone suggest a cleaner one? I'm working in AS3, but feel free to provide a more generic solution.

A: 

Hey there!

One possible solution is to have your products implement a getType() method. This could just return a string, or int that is unique to that product type. You could dynamically create unique arrays for product types as they come up (ie: check if array exists for type, create if needed before storing) or alternatively, you could just store all product types in one array, and have filter functions for retrieving them. An example of this would be:

function getProductsByType(type:String):Array {
    var matched:Array = [];
    for(//loop over all products) {
        //if type is what your looking for, push into matched array
    }

    return matched;
}
Tyler Egeto
I do actually need to keep them separate for my specific implementation, but good info. If I do what I stated above, which is what I'm leaning towards, I can do it dynamically. I'm not sure of another way to dynamically create Arrays/Dictionaries with Strings. Such that I can use the Dictionary's key with the string to make reference to the new Dictionary/Array.
grey
There is certainly nothing wrong with that solution. As long as you don't have to manually add a new array for each type.
Tyler Egeto