DESIGN PATTERNS – PROTOTYPE

Prototype design pattern. You should use it whenever you need to clone model classes. A simple example is when you have 1000 clients and you need to provide them invoices. Then, you only need to change e,g, names, surnames and total amount – you don’t need to create another invoice from the beginning. Again, the same situation is when your class is a parent for other classes – in this situation, it is not easy to create new – you should clone existing instance and then try to modify it.

Here is a simple example of creating such design pattern:

1) You need to create a Prototype (Model) class. In this case it will be DocumentPrototype.cs:

1

Let’s look inside DocumentPrototype.cs:

namespace MyDesignPatterns.Prototype
{
    internal class DocumentPrototype
    {
        public string DocumentPrototypeName { get; set; }

        public int DocumentPrototypeSize { get; set; }

        public DocumentPrototype(string documentName, int documentSize)
        {
            DocumentPrototypeName = documentName;
            DocumentPrototypeSize = documentSize;
        }

        public DocumentPrototype ClonePrototype()
        {
            return MemberwiseClone() as DocumentPrototype;
        }
    }
}

The only new thing in this class is ClonePrototype() method. It is responsible for cloning our object. MemberwiseClone() is a method from Object class. Of course you can also implement your own class with clone method instead of this.

In Program.cs you should have similar code:

using System;

namespace MyDesignPatterns
{
    using MyDesignPatterns.Prototype;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var firstOriginalDocument = new DocumentPrototype("Document1", 5);

            for (var i = 0; i < 10; ++i)
            {
                DocumentPrototype copiedDocumentPrototype = firstOriginalDocument.ClonePrototype();
                Console.WriteLine(copiedDocumentPrototype.DocumentPrototypeName);

                copiedDocumentPrototype.DocumentPrototypeName = "ModifiedDocument1";
                Console.WriteLine(copiedDocumentPrototype.DocumentPrototypeName + Environment.NewLine);
            }

            Console.ReadKey();
        }
    }
}

You can see that it is really easy to use prototype. You are able to modify the copied instance easily. Of course as in previous article about Facade, I suggest to use interfaces.

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

Connecting to %s