Skip to content

Instantly share code, notes, and snippets.

@simongarisch
Created October 16, 2019 03:01
Show Gist options
  • Save simongarisch/ef152e9726beaaa539cd241a8cc82e04 to your computer and use it in GitHub Desktop.
Save simongarisch/ef152e9726beaaa539cd241a8cc82e04 to your computer and use it in GitHub Desktop.
Python structural patterns - flyweight
# minimize memory usage with data sharing.
from enum import Enum
PresidentType = Enum("President", "Bush Clinton")
class President:
objects = dict()
def __new__(cls, president_type):
obj = cls.objects.get(president_type)
if obj is None:
obj = super().__new__(cls)
cls.__init__(obj, president_type)
cls.objects[president_type] = obj
return obj
def __init__(self, president_type):
self.president_type = president_type
clinton1 = President(PresidentType.Clinton)
clinton2 = President(PresidentType.Clinton)
print(clinton1 is clinton2) # True
bush1 = President(PresidentType.Bush)
bush2 = President(PresidentType.Bush)
print(bush1 is bush2) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment