Skip to content

Commit f6d5a49

Browse files
author
Jeeven Dhanoa
committed
add singleton
1 parent e528159 commit f6d5a49

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

app/data/__init__.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
from ..services.location.csbs import CSBSLocationService
33
from ..services.location.jhu import JhuLocationService
44
from ..services.location.nyt import NYTLocationService
5+
from ..utils.singleton import Singleton
56

67

7-
class DataSources:
8+
class DataSources(Singleton):
89
"""
910
Class to represent the root of the aggregate containing the location services.
1011
"""
@@ -16,9 +17,16 @@ class DataSources:
1617
"nyt": NYTLocationService(),
1718
}
1819

20+
__instance = None
21+
1922
def __init__(self):
2023
pass
2124

25+
def get_instance():
26+
if DataSources.__instance is None:
27+
DataSources.__instance = DataSources()
28+
return DataSources.__instance
29+
2230
def get_data_source(self, source):
2331
"""
2432
Retrieves the provided data-source service.

app/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
on_shutdown=[teardown_client_session],
4242
)
4343

44-
DATA_SOURCES = DataSources()
44+
DATA_SOURCES = DataSources.get_instance()
4545

4646
# #####################
4747
# Middleware

app/routers/v2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from ..models import LatestResponse, LocationResponse, LocationsResponse
88

99
V2 = APIRouter()
10-
DATA_SOURCES = DataSources()
10+
DATA_SOURCES = DataSources.get_instance()
1111

1212

1313
class Sources(str, enum.Enum):

app/utils/singleton.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Singleton(object):
2+
def __new__(cls, *args, **kwds):
3+
it = cls.__dict__.get("__it__")
4+
if it is not None:
5+
return it
6+
cls.__it__ = it = object.__new__(cls)
7+
it.init(*args, **kwds)
8+
return it
9+
10+
def init(self, *args, **kwds):
11+
pass

0 commit comments

Comments
 (0)