isereda

Spotify Factory Example

May 26th, 2020
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. from typing import Union
  2.  
  3.  
  4. class SpotifyObjectTypeEnum:
  5.     ALBUM = 'album'
  6.     TRACK = 'track'
  7.  
  8.  
  9. class SpotifyObjectCollectionDTO(list):
  10.     pass
  11.  
  12.  
  13. class AlbumCollectionDTO(SpotifyObjectCollectionDTO):
  14.     pass
  15.  
  16.  
  17. class TrackCollectionDTO(SpotifyObjectCollectionDTO):
  18.     pass
  19.  
  20.  
  21. class SpotifyResultDTO:
  22.     def __init__(self, albums: AlbumCollectionDTO, tracks: TrackCollectionDTO):
  23.         self.__albums = albums
  24.         self.__tracks = tracks
  25.  
  26.  
  27. class SpotifyAlbumDTO:
  28.     def __init__(self, title: str, year: int):
  29.         self.__title = title
  30.         self.__year = year
  31.  
  32.  
  33. class SpotifyTrackDTO:
  34.     def __init__(self, title: str, duration: int):
  35.         self.__title = title
  36.         self.__duration = duration
  37.  
  38.  
  39. class SpotifyAlbumFactory:
  40.     @staticmethod
  41.     def build(data: dict) -> SpotifyAlbumDTO:
  42.         return SpotifyAlbumDTO(
  43.             title=data.get('title'),
  44.             year=data.get('year'),
  45.         )
  46.  
  47.  
  48. class SpotifyTrackFactory:
  49.     @staticmethod
  50.     def build(data: dict) -> SpotifyTrackDTO:
  51.         return SpotifyTrackDTO(
  52.             title=data.get('title'),
  53.             duration=data.get('duration'),
  54.         )
  55.  
  56.  
  57. class SpotifyObjectCollectionFactory:
  58.     @staticmethod
  59.     def build(data: dict, object_type: str) -> Union[AlbumCollectionDTO, TrackCollectionDTO]:
  60.         collection_map = {
  61.             SpotifyObjectTypeEnum.ALBUM: AlbumCollectionDTO,
  62.             SpotifyObjectTypeEnum.TRACK: TrackCollectionDTO,
  63.         }
  64.         factory_map = {
  65.             SpotifyObjectTypeEnum.ALBUM: SpotifyAlbumFactory,
  66.             SpotifyObjectTypeEnum.TRACK: SpotifyTrackFactory,
  67.         }
  68.  
  69.         collection = collection_map.get(object_type)()
  70.         item_factory = factory_map.get(object_type)
  71.  
  72.         for key, item_data in data:
  73.             collection.append(item_factory.build(item_data))
  74.  
  75.         return collection
  76.  
  77.  
  78. class SpotifyResultFactory:
  79.     @staticmethod
  80.     def build(data: dict) -> SpotifyResultDTO:
  81.         return SpotifyResultDTO(
  82.             albums=SpotifyObjectCollectionFactory.build(data.get('albums'), 'album'),
  83.             tracks=SpotifyObjectCollectionFactory.build(data.get('tracks'), 'track'),
  84.         )
Add Comment
Please, Sign In to add comment