Created
February 27, 2014 18:10
-
-
Save eloraburns/9255557 to your computer and use it in GitHub Desktop.
Strategies, staticmethods, modules, OH MY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://en.wikipedia.org/wiki/Strategy_pattern | |
# class_strategy.py: | |
# class IntegerStrategy(object): | |
# @staticmethod | |
# def add(a, b): | |
# ... | |
# class FloatStrategy(object): | |
# @staticmethod | |
# def add(a, b): | |
# ... | |
# module_strategy/integer_strategy.py: | |
# def add(a, b): | |
# ... | |
# module_strategy/float_strategy.py: | |
# def add(a, b): | |
# ... | |
from class_strategy import IntegerStrategy, FloatStrategy, DecimalFloatStrategy | |
from module_strategy import integer_strategy, float_strategy, decimal_float_strategy | |
def f(x, strategy): | |
y = strategy.add(x, x) | |
# So do you like: | |
print f(1, IntegerStrategy) | |
# Or: | |
print f(1, integer_strategy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
… but when you're doing this, you almost always want to have some state along with the strategy, and then you're just using a plain old class-with-methods.
For example, maybe you want to include overflow handling: