The decorator design pattern, behold the power of interfaces!

The decorator design pattern uses an interface to add functionality to a class without extending it. Another name for ‘adding functionality’ is ‘decorating’. You can spot a decorator because it implements an interface and accepts the same interface in its constructor.

class MyDecorator implements MyInterface
{
    private MyInterface my_interface

    public construct(MyInterface my_interface)
    {
        this.my_interface = my_interface
    }

    public doWork()
    {
        this.my_interface.doWork()
        this.doAdditionalWork()
    }
}

MyDecorator decorates any MyInterface implementation with this.doAdditionalWork(), while also doing the original work with this.my_interface.doWork().

Anywhere the interface is referenced, the decorator can be used, so additional work can be added without class extension and without modifying any calling code.

Behold the power of interfaces!

Home