Python Design Pattern

ifeelfree
2 min readJan 23, 2021

Part 1: Factory and Abstract Factory

The Abstract Factory Pattern is a creational pattern that adds an abstract layer over multiple factory method implementations.

The Abstract Factory pattern differs from the Factory Pattern in that it returns Factories, rather than objects of concrete class.

Part 2: Observer

The observer pattern is a software design pattern in which an object, called the subject or observable, manages a list of dependents, called observers, and notifies them automatically of any internal state changes, and calls one of their methods.

from abc import ABCMeta, abstractmethod
from enum import Enum
import time
class WeatherType(Enum):
SUNNY = 1
RAINY = 2
WINDY = 3
COLD = 4
from abc import ABCMeta, abstractmethod
from enum import Enum
import time
class WeatherType(Enum):
SUNNY = 1
RAINY = 2
WINDY = 3
COLD = 4
class IObserver(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def notify(weather_type):
"""Update all the subscribed observers"""
class BBCWeather(IObserver):
def __init__(self, observable):
observable.subscribe(self)
def notify(self, weather_type):
print(f"{__class__} : {repr(weather_type)}")

class ABCWeather(IObserver):
def __init__(self, observable):
observable.subscribe(self)
def notify(self, weather_type):
print(f"{__class__} : {repr(weather_type)}")

class NBCWeather(IObserver):
def __init__(self, observable):
observable.subscribe(self)
def notify(self, weather_type):
print(f"{__class__} : {repr(weather_type)}")
WEATHERSERVICE = Weather()BBCWEATHER = BBCWeather(WEATHERSERVICE)
ABCWEATHER = ABCWeather(WEATHERSERVICE)
NBCWEATHER = NBCWeather(WEATHERSERVICE)
WEATHERSERVICE.notify(WeatherType.RAINY)

The output will be:

<class '__main__.NBCWeather'> : <WeatherType.RAINY: 2>
<class '__main__.ABCWeather'> : <WeatherType.RAINY: 2>
<class '__main__.BBCWeather'> : <WeatherType.RAINY: 2>

Reference

--

--