Reverse and stacking

Step 3: Reverse and stacking

The real power of the pattern shows up when you stack decorators. Because every decorator has the same read() interface, one decorator can wrap another, forming a chain. When you call read() on the outermost wrapper, the call travels inward to the Source and the transformed result bubbles back out, each layer applying its change in turn.

Implement Reverse, whose read() returns the wrapped text reversed. Then note how UpperCase(Reverse(Source("abc"))) works: Reverse runs first on the source, and UpperCase transforms whatever Reverse produced. The order of wrapping determines the order of transformation.

Hints
Starter code
class Source:
    def __init__(self, text):
        self.text = text

    def read(self):
        return self.text


class Decorator:
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def read(self):
        return self.wrapped.read()


class UpperCase(Decorator):
    def read(self):
        return self.wrapped.read().upper()


class Reverse(Decorator):
    def read(self):
        """Return the wrapped text reversed."""
        # TODO:
        #   return self.wrapped.read()[::-1]
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.