Search code examples
c#design-patternsdecoratorcomposition

Decorator Pattern Using Composition Instead of Inheritance


My previous understanding of the decorator pattern was that you inherit Window with WindowDecorator, then in the overridden methods, do some additional work before calling the Window's implementation of said methods. Similar to the following:

public class Window
{
    public virtual void Open()
    {
        // Open the window
    }
}

public class LockableWindow : Window // Decorator
{
    public virtual void Open()
    {
        // Unlock the window
        base.Open();
    }
}

However this essentially hardcodes the decoration, so how would this be refactored to use composition instead of inheritance?


Solution

  • Sorry, my C# is a a bit (OK, very) rusty, so there may be a few syntax errors, but the basic idea is right.

    public interface IWindow
    {
        void Open();
    }
    
    public class Window : IWindow
    {
        public virtual void Open()
        {
            // Open the window
        }
    }
    
    public class LockableWindow : IWindow
    {
        private IWindow _wrappedWindow;
    
        public LockableWindow(IWindow wrappedWindow)
        {
            _wrappedWindow = wrappedWindow;
        }
    
        public virtual void Open()
        {
            // TODO Unlock window if necessary
            _wrappedWindow.open();
        }
    }
    

    The key thing to notice is the new IWindow interface; that's what allows you to keep using polymorphism.