0

In my problem I had lots of objects with slightly different behaviour, but identical attributes and methodes with identical interfaces. The objects variants were quite big in number, and I didn't want to create a class for each of them, with lots of repeting code.

I circumvented creating a lot of derived classed by the following construct (pseudocode for abbrevation)

#aTP = all the parameters
def _function_version_1(aTP):
    ...

...

def _function_version_BIG(aTP):
    ...

class BaseClass(object):
    _typesOfImplementation = {'ONE' : _function_version_1,
                               ...
                              'BIG' : _function_version_BIG,
                             }

    def __init__(self, type, ...)
        ...
        if type not in _typesOfImplementation:
            raise Exception('Unknown type')
        # respective function for this object
        self.function = lambda aTP:BaseClass._typesOfImplementation[type](self, aTP)

Is this still an implementation of the strategy pattern, although I didn't use classes for the respective function version (which would have been an awful bunch of classes again)?

3

I would say no. One of the key points of strategy pattern is ability to add new types of strategies without having to change the base class. In your case, you would need to add new item into _typesOfImplementation, thus changing the base class. Also, with strategy pattern, you can change the strategy during the base class's lifetime. Your code has the strategy hard-wired during the base's construction.

  • Are both arguments of you "no-gos'" for strategy pattern? I'm just asking for clarification of the definition, a deeper understanding of the term. The above solution works fine for me – Lord_Gestalter Apr 25 '14 at 5:37
  • @Lord_Gestalter I think calling your code a strategy pattern would definitely introduce some kind of confusion. But then the question is how to call it. Maybe calling it "Strategy but with [name all the limitations here]" could work. – Euphoric Apr 25 '14 at 5:48
  • I'm reading Design Patterns by Go4 right now and compare my former work with it. Searching for pattern I used, similarities and differences. Where I might improve or refactor. Like I said, the above works fine, I won't change that part. But when I introduce someone to my work, e.g for review I don't want to misuse or twist terms. That's all, I don't have to give it a name. Thanks for the help – Lord_Gestalter Apr 25 '14 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.