8.4. Façade

8.4.1. Rationale

  • EN: Façade

  • PL: Fasada

  • Type: object

8.4.2. Use Cases

  • Provide simple interface to complex system

8.4.3. Problem

  • Every time we want to send a push notification to users, we need to follow all steps:

    • connect() -> Connection

    • authenticate(appid, key) -> AuthToken

    • send(AuthToken, message, target)

    • conn.disconnect()

from dataclasses import dataclass


@dataclass
class Message:
    __content: str


class Connection():
    def disconnect(self) -> None:
        pass


class AuthToken:
    pass


class NotificationServer:
    """
    connect() -> Connection
    authenticate(appid, key) -> AuthToken
    send(AuthToken, message, target)
    conn.disconnect()
    """

    def connect(self, ip_address: str) -> Connection:
        return Connection()

    def authenticate(self, appid: str, key: str) -> AuthToken:
        return AuthToken()

    def send(self, authtoken: AuthToken, message: Message, target: str):
        print('Sending a message')


if __name__ == '__main__':
    server = NotificationServer()
    connection = server.connect('127.0.0.1')
    authtoken = server.authenticate('AppId', 'Key')
    message = Message('Hello World')
    server.send(authtoken, message, '192.168.0.1')
    connection.disconnect()

8.4.4. Design

8.4.5. Implementation

../../_images/designpatterns-facade-usecase.png
from dataclasses import dataclass


@dataclass
class Message:
    __content: str


class Connection():
    def disconnect(self) -> None:
        pass


class AuthToken:
    pass


class NotificationService:
    def send(self, message: str, target: str) -> None:
        server = NotificationServer()
        connection = server.connect('127.0.0.1')
        authtoken = server.authenticate('AppId', 'Key')
        server.send(authtoken, Message(message), target)
        connection.disconnect()


class NotificationServer:
    """
    connect() -> Connection
    authenticate(appid, key) -> AuthToken
    send(AuthToken, message, target)
    conn.disconnect()
    """

    def connect(self, ip_address: str) -> Connection:
        return Connection()

    def authenticate(self, appid: str, key: str) -> AuthToken:
        return AuthToken()

    def send(self, authtoken: AuthToken, message: Message, target: str):
        print('Sending a message')


if __name__ == '__main__':
    service = NotificationService()
    service.send('Hello World', '192.168.0.1')

8.4.6. Assignments

  • Clean datetime

  • Split name into firstname and lastname

  • Example from @staticmethod chapter