5/20/2026

Prototype Design Pattern

✅ Definition Prototype Pattern = Create new objects by cloning an existing object instead of creating from scratch, which improves performance by avoiding repeated expensive initialization, reduces CPU work, and allows reuse of preconfigured object state. 🤔 Why use it? Used when object creation is slow, complex, or repeated, and you want to reuse an existing object as a template instead of rebuilding it every time.

📊 Comparison
AspectWithout Prototype (new)With Prototype (clone)
CreationBuild from scratchCopy existing
Speed❌ Slow✅ Fast
CPU❌ High✅ Low
Memory✅ Same✅ Same
Use caseSimple objectsComplex/expensive objects
Risk✅ Safe⚠️ Copy issues

🔁 Shallow vs Deep Copy

TypeDescriptionSpeedRisk
ShallowCopies references✅ Fast❌ Shared data
DeepFull independent copy❌ Slower✅ Safe

var r1 = new Report();
var r2 = new Report(); // expensive again

using System;

class Report : ICloneable
{
    public string Data;

    public Report()
    {
        Console.WriteLine("Expensive creation...");
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

// Usage
var original = new Report();
var copy1 = (Report)original.Clone();
var copy2 = (Report)original.Clone();


public object Clone()
{
    return new Report
    {
        Data = this.Data
    };
}

No comments:

Post a Comment