# Prototype

> Clone existing objects instead of constructing from scratch — the object knows how to copy itself, keeping internals private.

- **Category**: Software Design
- **Subcategory**: creational
- **Canonical URL**: https://designpattern.fyi/patterns/prototype/

---

## Description
**Intent**: Create new objects by copying existing configured ones, without depending on their concrete class or re-running expensive initialization.

**Context**: You need to duplicate complex objects — game entities, configured document templates, pre-built UI components — but constructing from scratch is expensive or requires knowing private implementation details. You want to stamp out copies of a 'prototype' instance.

**Solution**: Add a `clone()` method to the object. It creates a copy of itself using whatever deep-copy logic is appropriate for its internals. Callers just call `clone()` — they don't need to know the class name, constructor parameters, or internal structure.


## Use Cases
Use when object creation is expensive (DB lookups, complex initialization), when you need many similar objects with slight variations, or when the exact class to instantiate isn't known.



## Implementation Example

```javascript
class Rectangle {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }
  clone() {
    return new Rectangle(this.width, this.height, this.color);
  }
}

const original = new Rectangle(10, 20, "blue");
const copy = original.clone();
console.log(copy !== original); // true

```



## Trade-offs


### Advantages

- Clone without coupling to the concrete class — work purely with the interface.

- Skip expensive re-initialization by cloning a pre-configured instance.




### Considerations & Drawbacks

- Deep cloning objects with circular references gets complicated fast.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/prototype)

