Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions factory-method-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# The Factory Method Pattern and Its Implementation in Python

This folder provides the code examples for the Real Python tutorial [The Factory Method Pattern and Its Implementation in Python](https://realpython.com/factory-method-python/).

## Setup

The examples run on Python 3.10 or later. Create and activate a virtual environment, then install the pinned dependencies:

```sh
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Only the YAML serializer needs PyYAML. Everything else uses the standard library.

## Usage

Each folder holds the modules for one part of the tutorial. Run the scripts from inside their folder, because the modules import each other by name:

- `song_serializer/original/`: the `SongSerializer` with complex conditional code, from *Introducing Factory Method*
- `song_serializer/refactored/`: the same serializer refactored to Factory Method, from *Basic Implementation of Factory Method*
- `object_serializer/`: the `ObjectSerializer` with the `SerializerFactory` object factory and the YAML format, from *An Object Serialization Example* through *Supporting Additional Formats*
- `music_services/`: the general purpose `ObjectFactory` and the specialized `MusicServiceProvider`, from *A General Purpose Object Factory* onward

```sh
$ cd song_serializer/original/
$ python demo.py
'{"id": "1", "title": "Water of Love", "artist": "Dire Straits"}'
'<song id="1"><title>Water of Love</title><artist>Dire Straits</artist></song>'
ValueError: YAML
```

```sh
$ cd object_serializer/
$ python demo.py
```

```sh
$ cd music_services/
$ python program.py
```
73 changes: 73 additions & 0 deletions factory-method-python/music_services/music.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import object_factory


class SpotifyService:
def __init__(self, access_code):
self._access_code = access_code

def test_connection(self):
print(f"Accessing Spotify with {self._access_code}")


class SpotifyServiceBuilder:
def __init__(self):
self._instance = None

def __call__(self, spotify_client_key, spotify_client_secret, **_ignored):
if not self._instance:
access_code = self.authorize(
spotify_client_key, spotify_client_secret
)
self._instance = SpotifyService(access_code)
return self._instance

def authorize(self, key, secret):
return "SPOTIFY_ACCESS_CODE"


class PandoraService:
def __init__(self, consumer_key, consumer_secret):
self._key = consumer_key
self._secret = consumer_secret

def test_connection(self):
print(f"Accessing Pandora with {self._key} and {self._secret}")


class PandoraServiceBuilder:
def __init__(self):
self._instance = None

def __call__(self, pandora_client_key, pandora_client_secret, **_ignored):
if not self._instance:
consumer_key, consumer_secret = self.authorize(
pandora_client_key, pandora_client_secret
)
self._instance = PandoraService(consumer_key, consumer_secret)
return self._instance

def authorize(self, key, secret):
return "PANDORA_CONSUMER_KEY", "PANDORA_CONSUMER_SECRET"


class LocalService:
def __init__(self, location):
self._location = location

def test_connection(self):
print(f"Accessing Local music at {self._location}")


def create_local_music_service(local_music_location, **_ignored):
return LocalService(local_music_location)


class MusicServiceProvider(object_factory.ObjectFactory):
def get(self, service_id, **kwargs):
return self.create(service_id, **kwargs)


services = MusicServiceProvider()
services.register_builder("SPOTIFY", SpotifyServiceBuilder())
services.register_builder("PANDORA", PandoraServiceBuilder())
services.register_builder("LOCAL", create_local_music_service)
12 changes: 12 additions & 0 deletions factory-method-python/music_services/object_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class ObjectFactory:
def __init__(self):
self._builders = {}

def register_builder(self, key, builder):
self._builders[key] = builder

def create(self, key, **kwargs):
builder = self._builders.get(key)
if not builder:
raise ValueError(key)
return builder(**kwargs)
22 changes: 22 additions & 0 deletions factory-method-python/music_services/program.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import music

config = {
"spotify_client_key": "THE_SPOTIFY_CLIENT_KEY",
"spotify_client_secret": "THE_SPOTIFY_CLIENT_SECRET",
"pandora_client_key": "THE_PANDORA_CLIENT_KEY",
"pandora_client_secret": "THE_PANDORA_CLIENT_SECRET",
"local_music_location": "/usr/data/music",
}

pandora = music.services.get("PANDORA", **config)
pandora.test_connection()
spotify = music.services.get("SPOTIFY", **config)
spotify.test_connection()
local = music.services.get("LOCAL", **config)
local.test_connection()

pandora2 = music.services.get("PANDORA", **config)
print(f"id(pandora) == id(pandora2): {id(pandora) == id(pandora2)}")

spotify2 = music.services.get("SPOTIFY", **config)
print(f"id(spotify) == id(spotify2): {id(spotify) == id(spotify2)}")
10 changes: 10 additions & 0 deletions factory-method-python/object_serializer/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import serializers
import songs
import yaml_serializer # noqa: F401 (registers the YAML format)

song = songs.Song("1", "Water of Love", "Dire Straits")
serializer = serializers.ObjectSerializer()

print(serializer.serialize(song, "JSON"))
print(serializer.serialize(song, "XML"))
print(serializer.serialize(song, "YAML"))
57 changes: 57 additions & 0 deletions factory-method-python/object_serializer/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import json
import xml.etree.ElementTree as et


class JsonSerializer:
def __init__(self):
self._current_object = None

def start_object(self, object_name, object_id):
self._current_object = {"id": object_id}

def add_property(self, name, value):
self._current_object[name] = value

def to_str(self):
return json.dumps(self._current_object)


class XmlSerializer:
def __init__(self):
self._element = None

def start_object(self, object_name, object_id):
self._element = et.Element(object_name, attrib={"id": object_id})

def add_property(self, name, value):
prop = et.SubElement(self._element, name)
prop.text = value

def to_str(self):
return et.tostring(self._element, encoding="unicode")


class ObjectSerializer:
def serialize(self, serializable, format):
serializer = factory.get_serializer(format)
serializable.serialize(serializer)
return serializer.to_str()


class SerializerFactory:
def __init__(self):
self._creators = {}

def register_format(self, format, creator):
self._creators[format] = creator

def get_serializer(self, format):
creator = self._creators.get(format)
if not creator:
raise ValueError(format)
return creator()


factory = SerializerFactory()
factory.register_format("JSON", JsonSerializer)
factory.register_format("XML", XmlSerializer)
10 changes: 10 additions & 0 deletions factory-method-python/object_serializer/songs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Song:
def __init__(self, song_id, title, artist):
self.song_id = song_id
self.title = title
self.artist = artist

def serialize(self, serializer):
serializer.start_object("song", self.song_id)
serializer.add_property("title", self.title)
serializer.add_property("artist", self.artist)
10 changes: 10 additions & 0 deletions factory-method-python/object_serializer/yaml_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import yaml
import serializers


class YamlSerializer(serializers.JsonSerializer):
def to_str(self):
return yaml.dump(self._current_object)


serializers.factory.register_format("YAML", YamlSerializer)
1 change: 1 addition & 0 deletions factory-method-python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PyYAML==6.0.4
12 changes: 12 additions & 0 deletions factory-method-python/song_serializer/original/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import serializer_demo as sd

song = sd.Song("1", "Water of Love", "Dire Straits")
serializer = sd.SongSerializer()

print(repr(serializer.serialize(song, "JSON")))
print(repr(serializer.serialize(song, "XML")))

try:
serializer.serialize(song, "YAML")
except ValueError as error:
print(f"ValueError: {error}")
29 changes: 29 additions & 0 deletions factory-method-python/song_serializer/original/serializer_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import json
import xml.etree.ElementTree as et


class Song:
def __init__(self, song_id, title, artist):
self.song_id = song_id
self.title = title
self.artist = artist


class SongSerializer:
def serialize(self, song, format):
if format == "JSON":
song_info = {
"id": song.song_id,
"title": song.title,
"artist": song.artist,
}
return json.dumps(song_info)
elif format == "XML":
song_info = et.Element("song", attrib={"id": song.song_id})
title = et.SubElement(song_info, "title")
title.text = song.title
artist = et.SubElement(song_info, "artist")
artist.text = song.artist
return et.tostring(song_info, encoding="unicode")
else:
raise ValueError(format)
12 changes: 12 additions & 0 deletions factory-method-python/song_serializer/refactored/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import serializer_demo as sd

song = sd.Song("1", "Water of Love", "Dire Straits")
serializer = sd.SongSerializer()

print(repr(serializer.serialize(song, "JSON")))
print(repr(serializer.serialize(song, "XML")))

try:
serializer.serialize(song, "YAML")
except ValueError as error:
print(f"ValueError: {error}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import json
import xml.etree.ElementTree as et


class Song:
def __init__(self, song_id, title, artist):
self.song_id = song_id
self.title = title
self.artist = artist


class SongSerializer:
def serialize(self, song, format):
serializer = get_serializer(format)
return serializer(song)


def get_serializer(format):
if format == "JSON":
return _serialize_to_json
elif format == "XML":
return _serialize_to_xml
else:
raise ValueError(format)


def _serialize_to_json(song):
payload = {
"id": song.song_id,
"title": song.title,
"artist": song.artist,
}
return json.dumps(payload)


def _serialize_to_xml(song):
song_element = et.Element("song", attrib={"id": song.song_id})
title = et.SubElement(song_element, "title")
title.text = song.title
artist = et.SubElement(song_element, "artist")
artist.text = song.artist
return et.tostring(song_element, encoding="unicode")
Loading