lundi 3 août 2020

Difference between shallow copy vs assignment and deep copy vs creating new object using new keyword in Prototype design pattern

So I'm learning about design patterns and today I came across Prototype design pattern. I created Prototype interface and it contains 2 methods ( CloneShallow and CloneDeep ). I created trivial class Employee which implements Prototype interface and has 2 properties( Id and FullName ) . The code is pretty straight forward.

public interface Prototype
{
    public Prototype CloneShallow();

    public Prototype CloneDeep();
}

public class Employee : Prototype
{
    public int Id { get; set; }

    public string FullName { get; set; }


    public Employee(int id,string fullName)
    {
        this.Id = id;
        this.FullName = fullName;
    }
    public Prototype CloneShallow()
    {
        return this;
    }

    public Prototype CloneDeep()
    {
        return new Employee(Id, FullName);
    }

    public void printInfo()
    {
        Console.WriteLine($"Id: {Id}");
        Console.WriteLine($"Full name: {FullName}");

    }
}

In main

class Program
    {
        static void Main(string[] args)
        {
            Employee original = new Employee(1, "First Employee");
            Employee copyPrototype = (Employee)original.CloneShallow();
            Employee copyAssigned = original;


            Employee deepCopy = (Employee)original.CloneDeep();
            Employee newDeepCopy = new Employee(original.Id, original.FullName);
            

        }
    }

I created object named original. After that i performed shallow copy with CloneShallow() method, whereas we have objects original and copyPrototype pointing to same address location. After that, I assigned object copyAssigned addres of object named original ( shallow copy aswel) .

In order to make deep copy of an original object, deepCopy object uses CloneDeep() method to allocate new memory space for it and newDeepCopy uses new keyword.

I am little bit confused. copyAssigned object is shallow copied same as copyProtoype (both of them are pointing to a same memory address) and newDeepCopy object is deep copied same as deepCopy object ( when created each of them has unique memory location with respective properties that are copied). I must be missing something, because I don't see the benefits from it.

Can anyone give a real world example of this pattern or atleast explain what is the use of it ?

Aucun commentaire:

Enregistrer un commentaire