โ† Back to Design Patterns
๐Ÿงฌ
Creational

Prototype

Creates new objects by cloning an existing instance rather than constructing from scratch.

The Problem

Creating a new object is expensive or complex. You need a copy that starts as an exact replica of an existing one, with only a few differences.

How It Works

  • โ€บCloning is often faster than constructing from scratch
  • โ€บDeep copy duplicates nested objects; shallow copy shares them โ€” know the difference
  • โ€บClone preserves the internal state that may be hard to reconstruct externally
  • โ€บThe client does not need to know the concrete class of the object
  • โ€บUseful for creating "template" objects with preset defaults

When to Use

โœ“Object construction is costly and a similar object already exists
โœ“Config or template objects shared as a starting point with minor variations
โœ“When you need to copy objects without depending on their concrete classes
โœ“Undo/redo โ€” snapshot the state by cloning before modification

Real-World Examples

๐ŸŽ
iOS

NSCopying / NSMutableCopying, UIImage copy, deep copy via NSKeyedArchiver

๐Ÿค–
Android

Kotlin data class .copy(), Parcelable, Bundle.clone()

๐ŸŒ
Web

structuredClone(), spread { ...obj }, Object.assign({}, obj)

Code Examples

Swift
final class Theme: NSCopying {
    var primaryColor: String
    var font: String
    var isDark: Bool

    init(color: String, font: String, dark: Bool) {
        primaryColor = color; self.font = font; isDark = dark
    }

    func copy(with zone: NSZone? = nil) -> Any {
        Theme(color: primaryColor, font: font, dark: isDark)
    }
}

let light = Theme(color: "#FF4D1C", font: "SF Pro", dark: false)
let dark   = light.copy() as! Theme
dark.isDark       = true
dark.primaryColor = "#FF6B47"

print(light.isDark)        // false โ€” original unchanged
print(dark.isDark)         // true