Post Details

What is the Prototype Design Pattern in C Sharp .Net ?

np

Fri , Aug 04 2023

np

Article 6 on design patterns-

Let understand  The Prototype Design Pattern

The Prototype Design Pattern is a creational design pattern that is used when creating an object is expensive or complex. It provides a mechanism for copying existing objects instead of creating new ones. Here is an example of the Prototype Design Pattern in C#:

using System;

public abstract class Prototype

{

   public int Id { get; set; }

    public abstract Prototype Clone();

}

public class ConcretePrototype1 : Prototype

{

    public override Prototype Clone()

    {

       return (Prototype)MemberwiseClone();

    }

}


public class ConcretePrototype2 : Prototype

{

    public override Prototype Clone()

    {

        return (Prototype)MemberwiseClone();

    }

}


class Program

{

   static void Main()

    {

        ConcretePrototype1 prototype1 = new ConcretePrototype1 { Id = 1 };

        ConcretePrototype1 clone1 = (ConcretePrototype1)prototype1.Clone();


        ConcretePrototype2 prototype2 = new ConcretePrototype2 { Id = 2 };

        ConcretePrototype2 clone2 = (ConcretePrototype2)prototype2.Clone();


        Console.WriteLine("Original: {0}, Clone: {1}", prototype1.Id, clone1.Id);

        Console.WriteLine("Original: {0}, Clone: {1}", prototype2.Id, clone2.Id);


        Console.ReadKey();

    }

}



Leave a Reply

Please log in to Comment On this post.