SoFunction
Updated on 2025-04-13

How to optimize the creation process by cloning objects

In software development, creating objects is a very common operation. However, in some cases, the process of constructing an object can be very complex or time consuming, especially when the creation of an object involves multiple steps or requires the initialization of a large amount of data. To solve this problem, the **Prototype Pattern** came into being. It allows the creation of new objects by copying an existing object, thus avoiding repeated creation costs and complex initialization processes.

What is prototype mode?

A prototype pattern is a creative design pattern that generates a new object by cloning an existing object instead of recreating a new instance. This not only improves efficiency, but also avoids repeated operations that occur during complex object creation. Prototype mode is especially suitable for the following scenarios:

  • The object construction process is relatively complicated, and directly copying existing objects can save time.
  • The creation process of an object requires frequent repetition, and the difference between each instance is only in the difference of a small number of attributes.

How the prototype mode works

Prototype mode enables copying of objects by providing a "clone method". Typically, this method returns a copy of the current object without rebuilding the entire object. The cloning of the object can beLight copy(Shallow Copy) orDeep copy(Deep Copy):

  • Light copy: The new object and the original object share a field of reference type (such as an array or a list) that points to the same memory address.
  • Deep copy: The new object not only copies the basic data of the original object, but also copies all objects pointed to by the reference type field, ensuring that the new object and the original object are completely independent.

How to implement prototype mode in C#?

1. Define the prototype interface

First, we need to define a prototype interface (usuallyICloneable), declare aClone()method. This method is used to clone objects.

public interface IPrototype
{
    IPrototype Clone();
}

2. Implement the prototype interface

Then, we implement specific classes, which will inherit fromIPrototypeInterface and implementClone()method. existClone()In methods, we usually copy all data of an object through a constructor or factory method.

public class ConcretePrototypeA : IPrototype
{
    public string Name { get; set; }
    public ConcretePrototypeA(string name)
    {
        Name = name;
    }
    // cloning method    public IPrototype Clone()
    {
        return new ConcretePrototypeA();
    }
}
public class ConcretePrototypeB : IPrototype
{
    public int Age { get; set; }
    public ConcretePrototypeB(int age)
    {
        Age = age;
    }
    // cloning method    public IPrototype Clone()
    {
        return new ConcretePrototypeB();
    }
}

3. Use prototypes to clone objects

In the application, we can callClone()Method to clone an existing object instead of recreating a new object.

class Program
{
    static void Main(string[] args)
    {
        // Create a prototype object        ConcretePrototypeA prototypeA = new ConcretePrototypeA("John");
        ConcretePrototypeB prototypeB = new ConcretePrototypeB(30);
        //Clone the prototype object        ConcretePrototypeA cloneA = (ConcretePrototypeA)();
        ConcretePrototypeB cloneB = (ConcretePrototypeB)();
        // Output the properties of the cloned object        ($"Original A: {}, Cloned A: {}");
        ($"Original B: {}, Cloned B: {}");
    }
}

Output result:

Original A: John, Cloned A: John
Original B: 30, Cloned B: 30

Shallow copy and deep copy

In practical applications,Clone()Methods can be implemented according to requirementsLight copyorDeep copy

  • Light copy: Share a field of reference type between objects. For example, if there are fields of array or collection type in an object, the cloned object and the original object share the same array or collection.
  • Deep copy: Ensure that the cloned object is completely independent and does not share any fields with the original object. All reference type fields will be recreated a new copy.

Here is an example of implementing deep copy:

public class ConcretePrototypeC : IPrototype
{
    public List<string> Items { get; set; }
    public ConcretePrototypeC(List<string> items)
    {
        Items = new List<string>(items); // Create a new list to ensure deep copy    }
    public IPrototype Clone()
    {
        // Deep copy: Create a new list        return new ConcretePrototypeC(new List<string>());
    }
}

In the above example,ItemsA field is a list. We can make sure that the clone object has a new list by copying the list content, thus achieving deep copying.

Application scenarios of prototype mode

Prototype mode is particularly useful in the following situations:

  • When the object creation overhead is high: If the object construction process is very complex and consumes resources (such as loading data through the network, database queries, etc.), you can use the prototype mode to create new objects by copying existing objects, thereby improving performance.
  • When a large number of similar objects are needed: If the program needs to create a large number of similar objects (such as configuration objects, cache objects, etc.), the prototype pattern can avoid repeated construction processes and generate new instances by cloning a template object.
  • Avoid unnecessary repetition: In some object creation process that requires repeated initialization, using prototype mode can avoid executing the same initialization code multiple times.

Summarize

Prototype mode creates new objects by cloning existing objects, which can avoid duplicate creation processes, especially for scenarios where the object creation process is complex or expensive. Implementing a prototype pattern in C# is very simple, mainly by defining aICloneableInterface and enable each concrete class to be implementedClone()Method to complete. Whether using shallow or deep copy, prototype mode can effectively improve the efficiency and flexibility of object creation.

By rationally using the prototype mode, the object creation process can be optimized in some specific scenarios to improve the performance and maintainability of the program.

This is the article about how to optimize the creation process by cloning objects. For more related content on C# prototype mode, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!