Question

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.

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top