September 19, 2024
design-pattern

Prototype Pattern

The prototype pattern creates a new object from the existing instance of the object. This pattern is used to create a duplicate object or clone of the current object to enhance performance.

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 = "john@mail.com";
      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 = "john@mail.com";
 
            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);
        }
 }

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

2 thoughts on “Prototype Pattern

Leave a Reply

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