When we create an object by using new keyword, it takes memory. If we create 1000 objects in a computer, we don’t care about its memory. Because we know that, computer has lot of memory. But think about mobile. Its memory is very low. If we create lot of objects for a mobile game, it will arise problem.

In this situation prototype pattern will help use. We will make a clone or prototype of a particular object. When we need that object, we will use the clone object. Every time we don’t need to create new object.

Consider the bellow Customer class.

public Customer Person
 {
        public String Name { get; set; }
        public String Email { get; set; }
 }
public static void Main(string[] args)
 {
      var customer= new Customer();
      customer.Name = "John Abrar";
      customer.Email = "[email protected]";
      Console.WriteLine("Name:{0} and Email:{1}", customer.Name, customer.Email);
 
 }

Now if we need to use this Customer class in 1000 places, we have to create 1000 objects. This is not good practice.

Let’s clone the Customer class.

public interface IClone
 {
   Object Clone();
 }
public class Customer : IClone
 {
     public String Name { get; set; }
     public String Email { get; set; }
     public Object Clone()
     {
          var customer= new Customer 
          {
                Name = Name,
                Email = Email
          };
 
            return customer;
     }
 }
public class Program
 {
        public static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.Name = "John Abrar";
            customer.Email = "[email protected]";
 
            Console.WriteLine("Before Cloning.......");
            Console.WriteLine("Name:{0} and Email:{1}", customer.Name, customer.Email);
 
            Customer customer1= customer.Clone() as Customer;
            Console.WriteLine("After Cloning..............");
            Console.WriteLine("Name:{0} and Email:{1}", customer1.Name, customer1.Email);
        }
 }

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *