Behavioral Patterns

Strategy

The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

class Context:
    def __init__(self, strategy):
        self.strategy = strategy
 
def add_strategy(a, b):
    return a+b
 
def subtract_strategy(a, b):
    return a-b
 
if __name__ == '__main__':
    for s in [add_strategy, subtract_strategy]:
        context = Context(s) 
        print context.strategy(3, 5)

8
-2

python/design_patterns/behavioral_patterns.txt · Last modified: 2011/01/06 by emilmont
CC Attribution-Noncommercial-Share Alike 3.0 Unported
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0