Skip to content

Instantly share code, notes, and snippets.

@shivamMg
Last active March 6, 2022 18:43
Show Gist options
  • Select an option

  • Save shivamMg/bfaf4519aa06147ba25a09d3bc0ea1d0 to your computer and use it in GitHub Desktop.

Select an option

Save shivamMg/bfaf4519aa06147ba25a09d3bc0ea1d0 to your computer and use it in GitHub Desktop.
Design patterns
from abc import ABC, abstractmethod
RED = 'RED'
YELLOW = 'YELLOW'
GREEN = 'GREEN'
class Light(ABC):
@property
@abstractmethod
def color(self):
pass
class Red(Light):
color = RED
class Yellow(Light):
color = YELLOW
class Green(Light):
color = GREEN
class Factory:
@staticmethod
def create_light(color):
if color == RED:
return Red()
elif color == YELLOW:
return Yellow()
elif color == GREEN:
return Green()
r = Factory.create_light(RED)
print(r.color)
# https://en.wikipedia.org/wiki/Observer_pattern#UML_class_and_sequence_diagram
# decoupled update of observers on subject's state change
# observers possibly called async
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
pass
def detach(self, observer):
pass
def notify(self):
for obs in self.observers:
obs.update()
class Observer:
def update(self): pass
class Singleton:
_instance = None
def __init__(self):
if Singleton._instance is None:
Singleton._instance = self
@staticmethod
def instance():
return Singleton._instance
if __name__ == '__main__':
# all will have same id:
s = Singleton()
print(s)
print(s.instance())
s2 = Singleton()
print(s2)
print(s2.instance())
# https://refactoring.guru/design-patterns/strategy
# runtime algorithm selection
from abc import ABC, abstractmethod
class Handler(ABC):
@abstractmethod
def execute(self):
pass
class HandlerA(Handler):
def execute(self):
return 'executed by A'
class HandlerB(Handler):
def execute(self):
return 'executed by B'
strategy_handler = {
'A': HandlerA(),
'B': HandlerB(),
}
if __name__ == '__main__':
strategy_handler['A'].execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment