Skip to content

Language support for the decorator design pattern #124

@lyubomyr-shaydariv

Description

@lyubomyr-shaydariv

Not sure if this one is worthy here, or even it this one could be useful. I mostly use decorators in favor of aggregation rather than inheritance. And there are situations when most of the methods, implemented from the interface, are simply delegated methods. Such methods can be easily generated with a compiler. This is more significant when the implemented interface is heavy and has a bunch of methods. It would be nice if it's allowed to implement necessary methods only, and let the compiler generate the rest of them. Let's say:

public interface IFoo {
    int Do1();
    int Do2();
    int Do3();
    int Do4();
    int Do5();
    int Do6();
    int Do7();
}

                            // +--- whatever nice thingy to denote a decorator
                            // V    decoratee must be an instance of IFoo
public sealed class Bar : IFoo for decoratee {

    // if we need a private constructor
    private Bar(IFoo decoratee) {
        this.decoratee = decoratee;
    }

    // ... and a factory method
    public static IFoo Bar(IFoo decoratee) {
        return new Bar(decoratee);
    }

    // then just decorate what's needed
    public int Do4() {
        Console.WriteLine("Do4() is decorated");
        return decoratee.Do4();
    }

    // the rest, Do1--Do3 and Do5--Do7 are automatically generated

}

UPDATE Feb 3, 2016

Kotlin supports the same feature with slightly different syntax: https://kotlinlang.org/docs/reference/delegation.html

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions