Saturday, September 12, 2009

The Decorator Pattern

Decorator pattern is a kind of structural design pattern which provides a way to attach new state and behavior to an object dynamically. The original object is left untouched which makes the pattern useful for changing systems. Decorators both inherit the original class and contain an instant of it.
The Decorator pattern is generally used when a object is needed with some extra functionality than an existing class but the existing class is not available for subclassing or one doesn't want to subclass for some reason (e.g. to avoid class explosion).
The following example illustrates the pattern:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DPPractice
{
    class DecoratorPattern
    {
        interface IWindow
        {
            string getDescription();
            void draw();
        }
        public class SimpleWindow : IWindow
        {
            public void draw()
            {
                //draw Simple Window
            }

            public string getDescription()
            {
                return "simple window";
            }

        }
        class VerticalScrollBarDecorator : IWindow
        {

            private IWindow decoratedWindow;

            public VerticalScrollBarDecorator(IWindow decoratedWindow)
            {
                this.decoratedWindow = decoratedWindow;
            }


            public void draw()
            {
                drawVerticalScrollBar();
                decoratedWindow.draw();
            }

            private void drawVerticalScrollBar()
            {
                // draw the vertical scrollbar
            }

            public String getDescription()
            {
                return decoratedWindow.getDescription() + ", including vertical scrollbars";
            }
        }

        static void Main(String[] args)
        {
            // create a decorated Window with horizontal and vertical scrollbars
            IWindow window = new VerticalScrollBarDecorator(new SimpleWindow());

            // print the Window's description
            Console.WriteLine(window.getDescription());
        }


    }
}





As can be seen from the example the Decorator pattern is heavily utilized in displaying windows etc. adding and excluding scroll bars easily while rendering.

Other uses of the Decorator Pattern:

1. Decorators are used in I/O API's of C#.
System.IO.Stream is decorated by
System.IO.BufferedStream
System.IO.FileStream Etc.

2. As illustrated by the example the Decorator pattern is heavily utilized in rendering windows/display objects

References:
http://en.wikipedia.org/wiki/Decorator_pattern
Design Patterns: Elements of Reusable Object-Oriented Software
C# 3.0 Design Patterns

No comments:

Related Posts with Thumbnails