jeudi 27 octobre 2016

Understanding Decorator Design Pattern in C#

I just started to learn Decorator Design Pattern, unfortunately i had to go through various refrences to understand the Decorator pattern in a better manner which led me in great confusion. so, as far as my understanding is concern, i believe this is a decorator pattern

interface IComponent
    {
        void Operation();
    }
    class Component : IComponent
    {
        public void Operation()
        {
            Console.WriteLine("I am walking ");
        }
    }
    class DecoratorA : IComponent
    {
        IComponent component;
        public DecoratorA(IComponent c)
        {
            component = c;
        }
        public void Operation()
        {
            component.Operation();
            Console.WriteLine("in the rain");
        }
    }
    class DecoratorB : IComponent
    {
        IComponent component;
        public DecoratorB(IComponent c)
        {
            component = c;
        }
        public void Operation()
        {
            component.Operation();
            Console.WriteLine("with an umbrella");
        }
    }
    class Client
    {
        static void Main()
        {
            IComponent component = new Component();
            component.Operation();

            DecoratorA decoratorA = new DecoratorA(new Component());
            component.Operation();

            DecoratorB decoratorB = new DecoratorB(new Component());
            component.Operation();

            Console.Read();
        }
    }

but can the below code also be Decorator Pattern?

class Photo
{
    public void Draw()
    {
        Console.WriteLine("draw a photo");
    }
}
class BorderedPhoto : Photo
{
    public void drawBorder()
    {
        Console.WriteLine("draw a border photo");
    }
}
class FramePhoto : BorderedPhoto
{
    public void frame()
    {
        Console.WriteLine("frame the photo");
    }
}
class Client
{
    static void Main()
    {
        Photo p = new Photo();
        p.Draw();

        BorderedPhoto b = new BorderedPhoto();
        b.Draw();
        b.drawBorder();

        FramePhoto f = new FramePhoto();
        f.Draw();
        f.drawBorder();
        f.frame();
    }
}

My Understanding

from the second example given by me, we can call all the three methods, but from the first example i wont be able to get access to all the three methods by creating a single object.

Aucun commentaire:

Enregistrer un commentaire