Skip to content

Instantly share code, notes, and snippets.

@mottosso
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mottosso/ff495c7a797b8aaeabb1 to your computer and use it in GitHub Desktop.
Save mottosso/ff495c7a797b8aaeabb1 to your computer and use it in GitHub Desktop.
Mockup of observer pattern in Python and C
// Observer pattern in C
#include <stdio.h>
// To pass and store functions, we need to define a function pointer
typedef void (*Signal)();
// We can the use this Signal as type for the contents of the `subscribers` array.
// We also keep track of how many subscribers there are currently, so as to
// not overwrite previously added signals.
int current = 0;
Signal subscribers[10]; // Only 10 subscribers are allowed at a time
// Make sure there is enough room for another subscriber
// then append the passed signal to the list of subscribers.
void connect(Signal signal) {
if(current <= 10) {
++current;
subscribers[current] = signal;
}
else
printf("Sorry, max number of subscribers reached");
}
// Test signals
void signalA(char *message) {
printf("SIGNAL A: %s\n", message);
}
void signalB(char *message) {
printf("SIGNAL B: %s\n", message);
}
void slot() {
// Slot to trigger connected signals, passing `argument`
for(int i = 0; i < sizeof(subscribers) / sizeof(Signal); ++i) {
Signal subscriber = subscribers[i];
if(subscriber)
subscriber("Hello");
}
}
int main(int argc, char *argv[]) {
connect(signalA);
connect(signalB);
slot();
return(0);
// outputs: "SIGNAL A: Hello\nSIGNAL B: Hello"
}
"""Observer pattern in Python"""
# Global list of connected signals
subscribers = []
def connect(signal):
"""Helper function for global list of signals"""
subscribers.append(signal)
def slot(argument):
"""Slot to trigger connected signals, passing `argument`"""
for subscriber in subscribers:
subscriber(argument)
# Test signals
def signal_a(message):
print("SIGNAL A: %s" % message)
def signal_b(message):
print("SIGNAL B: %s" % message)
if __name__ == '__main__':
connect(signal_a)
connect(signal_b)
slot("Hello")
# outputs: "SIGNAL A: Hello\nSIGNAL B: Hello"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment