Demo entry 6776232

Facade

   

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

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:
    _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()


if __name__ == '__main__':

    HeroFacade.create_heroes()
    HeroFacade.call_heroes()

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).