Demo entry 6776241

Composite

   

Submitted by anonymous on Nov 30, 2018 at 13:04
Language: Python. Code size: 1.2 kB.

import abc


class Elf:
    name = 'Rosalor'

    def move(self, x, y):
        print(f'{self.name} is moving to {x} {y}')


class Orc:
    name = 'Khadgar'

    def move(self, x, y):
        print(f'{self.name} is moving to {x} {y}')


class Human:
    name = 'Severus Smithy'

    def move(self, x, y):
        print(f'{self.name} is moving to {x} {y}')


class Component(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def move(self, x, y):
        pass


class Composite(Component):

    def __init__(self):
        self._children = set()

    def move(self, x, y):
        for child in self._children:
            child.move(x, y)

    def add(self, component):
        self._children.add(component)

    def remove(self, component):
        self._children.discard(component)


def main():
    human = Human()
    elf = Elf()
    composite = Composite()
    composite.add(human)
    composite.add(elf)

    composite.move(x=100, y=100)
    composite.remove(elf)

    composite.move(x=200, y=200)


if __name__ == "__main__":
    main()


Severus Smithy is moving to 100 100
Rosalor is moving to 100 100
Severus Smithy is moving to 200 200

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).