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:


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();

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


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

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s