Demo entry 6776237

Full example

   

Submitted by anonymous on Nov 30, 2018 at 12:59
Language: Python. Code size: 2.8 kB.

import abc


class Observer(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def update(self, obj, *args, **kwargs):
        pass


class Observable:
    def __init__(self):
        self._observers = []

    def add_observer(self, observer):
        self._observers.append(observer)

    def remove_observer(self, observer):
        self._observers.remove(observer)

    def notify_observer(self, *args, **kwargs):
        for observer in self._observers:
            observer.update(self, *args, **kwargs)


class Elf:
    name = 'Rosalor'

    def le_suilon(self):
        print('Elf {name} says: Greeting'.format(name=self.name))


class Orc:
    name = 'Khadgar'

    def mok_rah(self):
        print('Orc {name} says: Greeting'.format(name=self.name))


class Human:
    name = 'Severus Smithy'

    def say_hello(self):
        print('Human {name} says: Greeting'.format(name=self.name))


class HeroAdapter(Observable):
    _initialised = False

    def __init__(self, hero, **adapted_methods):
        super().__init__()

        self.hero = hero

        for key, value in adapted_methods.items():
            func = getattr(self.hero, value)
            self.__setattr__(key, func)

        self._initialised = True

    def __getattr__(self, attr):
        return getattr(self.hero, attr)

    def __setattr__(self, key, value):
        if not self._initialised:
            super().__setattr__(key, value)
        else:
            setattr(self.hero, key, value)
            self.notify_observer(key=key, value=value)


class HeroFacade:
    hero_adapters = None

    @classmethod
    def create_heroes(cls):
        print('Creating heroes ...')
        cls.hero_adapters = [
            HeroAdapter(Human(), call_me='say_hello'),
            HeroAdapter(Elf(), call_me='le_suilon'),
            HeroAdapter(Orc(), call_me='mok_rah')
        ]

    @classmethod
    def call_heroes(cls):
        print('Call heroes ...')
        for adapter in cls.hero_adapters:
            adapter.call_me()

    @classmethod
    def monitor_elves(cls, observer):
        cls.hero_adapters[0].add_observer(observer)
        print('Added an observer to the Elves!')

    @classmethod
    def change_elves_name(cls, new_name):
        print('Changing the Elves name ...')
        cls.hero_adapters[0].name = new_name
        print('Elves name changed!')


class Player(Observer):
    def update(self, obj, *args, **kwargs):
        print(f'Object: {obj}, Args: {args}, Kwargs: {kwargs}')


if __name__ == '__main__':
    player = Player()

    HeroFacade.create_heroes()
    HeroFacade.monitor_elves(player)
    HeroFacade.change_elves_name('Elrond')

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).