Difference between facade and Decorator Pattern

Yesterday, I was discussing with friends – What is the differences between facade and decorator pattern? Facade gives the impression that your create a facade object over different desperate objects,  and decorate gives the impression that your decorate couple of objects with another layer. Are they two different name for the same pattern? All kind of confusion was there, because of name I noticed people get confused between these two pattern.

With this blog entry, I want to make sure that you will never ever forget their definition and never get mixed up between these two patterns.

Decorator pattern is a design pattern that allows new/additional behavior to be added to an existing class dynamically. Decorators provide a flexible alternative to sub classing for extending functionality.

The decorator pattern can be used to make it possible to extend (decorate) the functionality of a class at runtime. Taking the example from Allan Shalloway book, Design patterns explained. Suppose you have to print a SalesTicket and depending up on sales, you may need to print multiple headers and multiple footers. Decorator pattern helps you control headers by chaining together the headers desired in the correct order.

Header1->Header2->Header3->Concrete Component.

beadneckles2 The Decorator pattern separates the dynamic building of this chain of functionality from the client. It will also separates the building of the chain from the chain components (Header and Footer).

Now, here is a way to remember it forever, a different way to think is, Decorator pattern help decorate. decorator pattern help us create  necklaces with different bead color combinations.  Decorator pattern is chain of objects. To achieve this you wrap the original bead class with a decorator class.

Suppose we need to write a program, which make different necklaces with different color combinations of beads. Because of decorator pattern it is fairly easy to build the different necklaces and the change in code can be limited to factory class.

Here is the code:

using System;

namespace Decorator
{

    ///
    /// The Beads abstract class
    ///

    abstract class Beads
    {
        public abstract void MakeNecklace();
    }

    ///
    /// The 'ConcreteComponent' class
    ///

    class ConcerteBead : Beads
    {

        public override void MakeNecklace()
        {
            Console.WriteLine("ConcreteBead");
        }
    }

    ///
    /// The 'Decorator' abstract class
    ///

    abstract class Decorator : Beads
    {
        protected Beads _beads;
        public Decorator(Beads beads)
        {
            this._beads = beads;
        }
        public Decorator()
        {
        }

        public override void MakeNecklace()
        {
            if (_beads != null)
            {
                _beads.MakeNecklace();
            }
        }
    }

    class RedBeads : Decorator
    {
        public RedBeads(Beads <span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="">beads)
        {
            _beads</span></span></span> = beads;
        }
        public override void MakeNecklace()
        {
            base.MakeNecklace();
            Console.WriteLine("RED");
        }
    }

    class GreenBeads : Decorator
    {
        public GreenBeads(Beads beads)
        {
            _beads = beads;
        }
        public override void MakeNecklace()
        {
            base.MakeNecklace();
            Console.WriteLine("GREEN");
        }
    }

    class WhiteBeads : Decorator
    {
        public WhiteBeads(Beads beads)
        {
            _beads = beads;
        }
        public override void MakeNecklace()
        {
            base.MakeNecklace();
            Console.WriteLine("WHITE");
        }
    }

    class Program
    {
        static void Main()
        {
            Beads beads = BeadFactory(true);
            beads.MakeNecklace();
            Console.ReadKey();
        }

        private static Beads BeadFactory(bool Colorful)
        {
            if (Colorful)
            {
                return new GreenBeads(new RedBeads(new WhiteBeads(new ConcerteBead())));
            }
            else
            {
                return new WhiteBeads(new WhiteBeads(new WhiteBeads(new ConcerteBead())));

            }
        }
    }
}

The output of the above code will be:

Concrete Bead
WHITE
RED
GREEN

Here is the stack trace:
decorator

So what exactly happening here? If you see the code
return new GreenBeads(new RedBeads(new WhiteBeads(new ConcerteBead())));

Green takes, Red in its constructor and Red takes White bead in its constructor. So when Green.MakeNecklace() is called, it calls base.MakeNecklace(), which is actually Decorator MakeNecklace(). and it in turn calls _beads.MakeNecklace(), which is actually Red. In other words, Green beads, _beads is set to Red bead by the chaining code shown above. Hope it is clear with the stack trace shown above, else copy paste the code in a project and run it.

To decouple client from the chain of object,  a factory objects can instantiate the chains based upon some configuration information.  Instantiation of the chains of objects is completely decoupled from the Client objects that use it. Decorator Allows for extending the functionality of an object without resorting to subclassing.

May be tomorrow we will talk about Facade pattern.

Advertisements

4 thoughts on “Difference between facade and Decorator Pattern

  1. Pingback: AOP – Interception with Unity | Tech Crumb - collected along the way ....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s