Skip to main content

Prototype: Creating New Objects by Copying Existing Ones

Design Patterns Explained: From Theory to Practice: Article 5

Updated 14 min readMarkdown
Part of seriesDesign Patterns

Creating objects from scratch is not always the most efficient approach.

Imagine a ticket-management application used by a support team. The team regularly handles different types of tickets, including critical incidents, access requests, and billing enquiries.

Each type of ticket has its own default configuration. A critical incident might have a high priority, an incident category, predefined tags, and a dedicated routing queue. An access request might use a different category, a normal priority, and an approval-related configuration.

If the application creates every ticket from scratch, it must repeatedly apply these configurations. We could introduce separate classes for every ticket type, but that would create additional subclasses simply to represent different configurations.

What if we could create a fully configured template once and use it as the starting point for new tickets?

This is where the Prototype pattern becomes useful.

What is the Prototype pattern?

Prototype is a creational design pattern that allows new objects to be created by copying existing objects, without requiring the client to depend on their concrete classes.

Instead of constructing an object and configuring all its properties every time, we create a preconfigured object called a prototype. When another object with similar characteristics is needed, we clone the prototype and make any necessary changes to the copy.

In our ticket-management application, this means creating predefined ticket templates and using them as starting points for new ticket drafts.

The important idea is that the application does not need to know the internal construction details of the object being copied. It only needs access to an operation that produces a copy.

Understanding the structure

The Prototype pattern typically involves three participants, with an optional fourth component:

Participant Ticket-management example Responsibility
Prototype IPrototype<T> Defines the operation used to create a copy
Concrete Prototype TicketDraft Implements the copying operation
Client TicketCreationService Requests a copy and customises it
Prototype Registry TicketPrototypeRegistry Stores and provides access to predefined prototypes

The prototype interface establishes a common contract for objects that support copying. Concrete prototypes implement that contract and determine how their own data should be copied.

The client interacts with the prototype abstraction rather than depending on the concrete implementation.

A prototype registry can also be introduced when an application needs to maintain a collection of frequently used prototypes. The registry allows clients to retrieve a prototype using a key or another selection criterion and receive a copy rather than the original object.

The registry is optional. A client can work directly with a prototype when maintaining a central catalogue provides no real benefit.

Implementing Prototype in C#

Let's implement the pattern using our ticket-management application.

We will create predefined configurations for critical incidents and access requests. Each configuration will act as a prototype from which new ticket drafts can be created.

Step 1: Define the prototype contract

Start by defining an interface that represents an object capable of producing a copy of itself.

public interface IPrototype<out T>
{
    T Clone();
}

The interface declares a single method, Clone(), which returns a copy of the current object.

Using a generic interface gives us a strongly typed return value rather than the object return type provided by the older ICloneable interface.

This means the client can work with the prototype abstraction without having to cast the returned object to a particular type.

Step 2: Define the object being copied

Next, create a TicketDraft class.

A draft represents the configurable information needed to create a ticket. It contains the title, description, priority, category, tags and metadata.

public enum TicketPriority
{
    Low,
    Normal,
    High,
    Critical
}

public enum TicketCategory
{
    General,
    Access,
    Incident,
    Billing
}

public sealed class TicketDraft : IPrototype<TicketDraft>
{
    public string Title { get; set; }

    public string Description { get; set; }

    public TicketPriority Priority { get; set; }

    public TicketCategory Category { get; set; }

    public List<string> Tags { get; }

    public Dictionary<string, string> Metadata { get; }

    public TicketDraft(
        string title,
        string description,
        TicketPriority priority,
        TicketCategory category,
        IEnumerable<string> tags,
        IDictionary<string, string> metadata)
    {
        Title = title;
        Description = description;
        Priority = priority;
        Category = category;

        Tags = new List<string>(tags);

        Metadata = new Dictionary<string, string>(
            metadata,
            StringComparer.OrdinalIgnoreCase);
    }

    public TicketDraft Clone()
    {
        return new TicketDraft(
            Title,
            Description,
            Priority,
            Category,
            Tags,
            Metadata);
    }
}

Notice that the constructor creates new collections from the supplied tags and metadata.

This is important because the draft contains mutable reference-type properties. We do not want a copied draft to share those collections with the original prototype.

The Clone() method creates a new TicketDraft using the existing object's values. The constructor then creates independent copies of its mutable collections.

We will explore why this matters when discussing shallow and deep copying.

Step 3: Create predefined prototypes

Now that we have a class capable of cloning itself, we can create our predefined ticket configurations.

var prototypes =
    new Dictionary<string, IPrototype<TicketDraft>>(
        StringComparer.OrdinalIgnoreCase)
{
    ["critical-incident"] = new TicketDraft(
        "Critical service incident",
        "Investigate the reported service disruption.",
        TicketPriority.Critical,
        TicketCategory.Incident,
        new[]
        {
            "incident",
            "customer-impact"
        },
        new Dictionary<string, string>
        {
            ["routing-queue"] = "major-incident"
        }),

    ["access-request"] = new TicketDraft(
        "Access request",
        "Review and process the requested access.",
        TicketPriority.Normal,
        TicketCategory.Access,
        new[]
        {
            "access",
            "approval-required"
        },
        new Dictionary<string, string>
        {
            ["approval-required"] = "true"
        })
};

We now have two preconfigured ticket drafts.

The critical incident prototype contains its default priority, category, tags and routing configuration. The access request prototype contains a different set of defaults.

Instead of repeating these configurations whenever a new ticket is created, the application can use the existing prototypes as starting points.

Step 4: Introduce a prototype registry

We can centralise access to these prototypes using a registry.

public sealed class TicketPrototypeRegistry
{
    private readonly IReadOnlyDictionary<
        string,
        IPrototype<TicketDraft>> _prototypes;

    public TicketPrototypeRegistry(
        IDictionary<string, IPrototype<TicketDraft>> prototypes)
    {
        var copies =
            new Dictionary<string, IPrototype<TicketDraft>>(
                StringComparer.OrdinalIgnoreCase);

        foreach (var (name, prototype) in prototypes)
        {
            copies.Add(name, prototype.Clone());
        }

        _prototypes = copies;
    }

    public TicketDraft CreateDraft(string name)
    {
        if (!_prototypes.TryGetValue(name, out var prototype))
        {
            throw new KeyNotFoundException(
                $"No ticket prototype named '{name}' was found.");
        }

        return prototype.Clone();
    }
}

The registry stores the prototypes using their names as keys.

When a client requests a particular ticket type, the registry looks up the corresponding prototype and calls Clone() to return a new draft.

Notice that the registry also clones the supplied prototypes when it is constructed. This prevents the original objects passed into the registry from being used to modify its internal templates later.

The registry never returns its stored prototypes directly. It always returns copies.

Step 5: Use the prototype

The client can now create a new ticket draft without knowing how its configuration was originally assembled.

var registry = new TicketPrototypeRegistry(prototypes);

var draft = registry.CreateDraft("critical-incident");

draft.Title = "Payment service unavailable";

draft.Description =
    "Customers cannot complete online payments.";

draft.Tags.Add("payments");

draft.Metadata["service"] = "checkout";

var ticket = ticketService.Create(requesterId, draft);

The application starts with the critical incident configuration and changes only the information specific to the new ticket.

The TicketCreationService can then validate the draft and create a new Ticket with its own identifier, initial status and creation timestamp.

Notice that the draft does not contain a ticket ID, requester ID or workflow status. These values belong to the new ticket, not the reusable template.

This is an important design consideration: a prototype should contain the state that makes sense to reuse, not necessarily every piece of state belonging to the original object.

Shallow copy vs deep copy

One of the most important considerations when implementing Prototype is understanding the difference between a shallow copy and a deep copy.

A shallow copy creates a new top-level object but copies references to any nested reference-type objects.

A deep copy creates independent copies of the referenced objects as well, to the extent required by the application's object model.

Consider what would happen if we implemented Clone() using MemberwiseClone():

public TicketDraft Clone()
{
    return (TicketDraft)MemberwiseClone();
}

The result would be a new TicketDraft instance, but its Tags and Metadata properties would still refer to the same collections as the original.

For example:

var original = registry.CreateDraft("critical-incident");

var clone = original.Clone();

clone.Tags.Add("urgent");

With a shallow copy, adding "urgent" to the cloned draft would also affect the original object's tags.

This is because MemberwiseClone() copies the references to those collections rather than creating new collections. Microsoft documents this behaviour in its Object.MemberwiseClone documentation.

Our earlier implementation avoids this problem by passing the original collections into a constructor that creates new instances of both collections.

For this particular model, that is sufficient because the collection elements are strings, which are immutable. If the collections contained other mutable objects, those objects would also need to be copied when independent state was required.

A deep copy is not automatically better in every situation. It requires more work and can become complicated when objects contain nested relationships, circular references, or references to external resources.

The important thing is to decide what should be shared and what must be independent.

When should you use Prototype?

Prototype is useful when creating an object from scratch involves repeated configuration, expensive initialisation, or knowledge of concrete classes that the client should not need.

Common scenarios include:

  • Preconfigured domain objects: Creating tickets, orders, or invoices from reusable templates.
  • Complex application configurations: Starting with an existing configuration and modifying only a few settings.
  • Test data generation: Creating test objects from known configurations rather than repeating lengthy setup logic.
  • Reducing subclass proliferation: Supporting different object configurations without creating a separate subclass for every variation.
  • Third-party integrations: Copying objects through a common abstraction when the concrete implementation is not known to the client.

The pattern is particularly useful when an application has a collection of frequently reused configurations and creating a new object from one of those configurations is easier than rebuilding it.

However, if constructing an object is inexpensive and straightforward, a normal constructor or factory may be all that is needed.

Advantages and disadvantages

Prototype offers several benefits, but copying objects introduces its own challenges.

Advantages

  • Reduces repeated initialisation: Preconfigured objects can be copied instead of being rebuilt every time.
  • Reduces coupling: Clients can work with a prototype abstraction rather than depending on concrete classes.
  • Avoids unnecessary inheritance: Different configurations can be represented by existing prototypes instead of creating many subclasses.
  • Supports complex configurations: Objects with numerous properties can be copied and customised without repeating all their setup logic.

Disadvantages

  • Copying can be complicated: Objects with nested references, circular relationships or complex internal state can be difficult to clone correctly.
  • Shared mutable state can cause bugs: A shallow copy may unintentionally allow changes to affect both the original and its copy.
  • Identity and lifecycle concerns: Copying an object should not necessarily copy its database identifier, status, timestamps or other state that must be unique.
  • Additional maintenance: Prototype interfaces, cloning methods and registries introduce extra code that may not be justified for simple objects.

The pattern is most effective when the benefits of reusing preconfigured objects outweigh the complexity of implementing and maintaining their copying behaviour.

Prototype in modern C# applications

C# provides several features that can make copying objects easier, so it is worth understanding how they relate to the Prototype pattern.

The MemberwiseClone() method

MemberwiseClone() is a protected method defined by System.Object. It creates a shallow copy of an object.

It can be useful when the object contains only value types and immutable references, or when sharing nested references is intentional.

However, it should not be treated as a general-purpose deep-copy operation. If an object contains mutable collections or other mutable objects, additional copying logic is required.

The ICloneable interface

.NET also provides the ICloneable interface, which defines a Clone() method.

The problem is that its contract does not specify whether the returned object should be a shallow copy or a deep copy.

This makes it difficult for callers to know exactly what they are receiving. Microsoft therefore recommends against implementing ICloneable in public APIs where predictable copying behaviour is important.

A strongly typed interface with explicit copying semantics is generally a better choice for application-specific requirements.

Records and with expressions

Modern C# records provide another convenient way to create copies of existing objects.

For example:

public sealed record TicketDefaults(
    TicketPriority Priority,
    TicketCategory Category,
    string RoutingQueue);

var standardDefaults = new TicketDefaults(
    TicketPriority.Normal,
    TicketCategory.General,
    "general-support");

var criticalDefaults = standardDefaults with
{
    Priority = TicketPriority.Critical,
    Category = TicketCategory.Incident,
    RoutingQueue = "major-incident"
};

The with expression creates a new record using the existing record as its starting point, while allowing selected properties to be changed.

This works particularly well for simple configuration objects containing value types and immutable reference types.

However, there is an important limitation: the with expression creates a shallow copy by default.

If a record contains a List<T>, array or dictionary, the copied record shares that reference unless the copy behaviour is explicitly customised.

C# record classes support custom copy constructors when different copying behaviour is required. You can read more in Microsoft's documentation on the with expression.

Records can therefore provide a lightweight way to copy simple objects, but they do not automatically replace every use of the Prototype pattern.

The distinction is that Prototype is a broader design approach involving preconfigured objects, a cloning contract and potentially a registry. A record's with expression is a language feature that makes creating modified copies convenient.

In a .NET application, a prototype registry can also be registered with dependency injection. A singleton registry can be appropriate when its stored prototypes are treated as read-only after initialisation and each request receives an independent copy. The mutable drafts returned by the registry should not be shared between concurrent operations.

Prototype vs Factory Method vs Abstract Factory vs Builder

We have now explored four creational design patterns. Although they all deal with object creation, their responsibilities are different.

Pattern Main responsibility Typical question
Factory Method Delegates the choice of concrete product creation Which implementation should be created?
Abstract Factory Creates families of related products Which compatible set of objects should be created?
Builder Controls step-by-step construction How should this complex object be assembled?
Prototype Creates objects by copying existing instances Can we start with an existing configuration and customise a copy?

Factory Method focuses on selecting an implementation.

Abstract Factory focuses on creating related products that belong together.

Builder focuses on controlling the steps required to construct a complex object.

Prototype focuses on reusing an existing object's configuration by copying it.

These patterns can sometimes be combined. For example, a prototype registry can behave like a specialised factory by locating a prototype and returning a clone.

The important distinction is the problem each pattern is intended to solve.

Conclusion

Prototype provides an alternative approach to object creation: instead of repeatedly constructing and configuring objects from scratch, we can create new instances by copying existing, preconfigured objects.

In our ticket-management application, predefined ticket configurations allow support teams to create new ticket drafts without repeating the same configuration steps.

However, implementing the pattern correctly requires careful consideration of what should be copied and what should remain independent. Shallow copying can introduce shared-state bugs, while deep copying can become complicated when objects have complex relationships.

Modern C# features such as records and with expressions can also simplify copying in less complicated scenarios.

The real skill is recognising when copying an existing configuration is more useful than constructing a new object from scratch.

The next article in the series explores Singleton, the final creational pattern in our sequence. It addresses a different concern: ensuring that a class has only one instance and providing a controlled way to access it.

Further reading

No comments yet. Be the first to comment.