Skip to content

Commit

Permalink
Add chapter_11 proxy pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
balancy committed Oct 12, 2023
1 parent 7a0c3bf commit dfe5a0e
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
1 change: 1 addition & 0 deletions patterns/chapter_11_proxy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Init file for chapter_11_proxy package."""
24 changes: 24 additions & 0 deletions patterns/chapter_11_proxy/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Proxy Pattern example module."""

import asyncio

from .remote_images import Proxy, RemoteImage


async def run_pattern_example() -> None:
"""Run proxy example.
While remote image is downloaded, proxy displays fake image.
"""
remote_image = RemoteImage()
proxy = Proxy(remote_image)

task1 = asyncio.create_task(remote_image.download())
task2 = asyncio.create_task(proxy.display())

await task1
await task2


if __name__ == "__main__":
asyncio.run(run_pattern_example())
61 changes: 61 additions & 0 deletions patterns/chapter_11_proxy/remote_images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Abstract Remote Image Interface, it's implementation and proxy."""
import asyncio
from abc import ABC, abstractmethod

DOWNLOAD_DELAY = 2
REFRESH_RATE = 0.5


class AbstractRemoteImage(ABC):
"""Abstract Remote Image Interface."""

@abstractmethod
async def display(self):
"""Abstract display method.
All child classes should implement this method.
"""
pass


class RemoteImage(AbstractRemoteImage):
"""Remote Image class."""

def __init__(self) -> None:
"""Initialize Remote Image.
It's not downloaded by default.
"""
self._is_downloaded = False

async def download(self):
"""Download the image."""
await asyncio.sleep(DOWNLOAD_DELAY)
self._is_downloaded = True

async def display(self):
"""Display the downloaded image."""
print('Displaying the downloaded image.')

@property
def is_downloaded(self) -> bool:
"""Check if the image is downloaded."""
return self._is_downloaded


class Proxy(AbstractRemoteImage):
"""Proxy class for Remote Image."""

def __init__(self, remote_image: RemoteImage) -> None:
"""Initialize Proxy."""
self._remote_image = remote_image

async def display(self):
"""Display the image.
Displays the fake image while the real image is downloading.
"""
while not self._remote_image.is_downloaded:
print('Displaying the fake image.')
await asyncio.sleep(REFRESH_RATE)
await self._remote_image.display()

0 comments on commit dfe5a0e

Please sign in to comment.