Last active
November 22, 2019 06:56
-
-
Save kpsychas/f721e897379fab590bf0545558e00dc5 to your computer and use it in GitHub Desktop.
Strategy pattern example in python with two different ways of providing a strategy
This file contains 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
import types | |
from functools import partial | |
class Resource1(object): | |
def __init__(self, value, update_strategy): | |
self.value = value | |
self.update = types.MethodType(update_strategy, self) | |
class Resource2(object): | |
def __init__(self, value, update_strategy): | |
self.value = value | |
self.update = partial(update_strategy, self) # alternative | |
class Update(object): | |
def __init__(self, resource_cls, n=1): | |
self.n = n | |
self.resource = resource_cls(0, self._update) | |
@property | |
def value(self): | |
return self.resource.value | |
def _update(self, resource): | |
resource.value += self.n | |
def run(self): | |
self.resource.update() | |
def main(): | |
def update(resource): | |
resource.value += 1 | |
def update_n(resource, n): | |
resource.value += n | |
for resource_cls in [Resource1, Resource2]: | |
x = resource_cls(0, update) | |
x.update() | |
print(x.value) | |
x = resource_cls(0, update_n) | |
x.update(2) | |
print(x.value) | |
z = Update(resource_cls) | |
z.run() | |
print(z.value) | |
z = Update(resource_cls, 2) | |
z.run() | |
print(z.value) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment