Implementing a callbacks in Python using Strategy Design Pattern
"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."
1. Callbacks are used in functional programming which takes an function but calls when certain certain conditions is met later in time.
2. Its similar to "Strategy Pattern" where the same piece of code must have different behavior for different invocation by different clients.
3. Primary use case is to switch implementation in OPEN CLOSED PRINCIPLE.
4. Behavior is selected in RUN-TIME.
#Strategies as CallBacks
class ReverseInt(object):def __init__(self):
self.description = "Integer Reverse Callbacks"
self.value = int
def __call__(self, val):return self.description, str(val)[::-1]
#Strategies as CallBacks
class ReverseStr(object):def __init__(self):
self.description = "String Reverse Callbacks"
self.value = str
def __call__(self, val):return self.description, val[::-1]
#ABSTRACTION Open for Extension
class Reverse(object):
def __init__(self):# Extensible Implementation of more callbacks
self._impls = [ReverseInt(),ReverseStr()]
def __call__(self, reverseme):"""select the strategy based on type parameter"""for impl in self._impls:
if impl.value == type(reverseme):
return impl(reverseme)
else:
return None
#But close for modification reverseFunction name cannot be changed
reverseFunction = Reverse()
# The Functions are unaware of implementations "Behavior is selected in RUNTIME"
print(reverseFunction(1234))
print(reverseFunction("abcde"))
Download the Complete Code: Code at REPL