Creational PatternsPrototype PatternMedium⏱️ ~3 min

Prototype Pattern in Document Editor

Scenario:

A document editor like Figma or Canva allows users to create shapes (rectangles, circles, text boxes) and duplicate them. Instead of rebuilding each shape with all its properties (color, position, border style, effects), we clone existing shapes. This is especially valuable when shapes have complex configurations or attached resources.

«interface»
Shape
+ clone(): Shape
+ draw(): void
+ setPosition(x, y): void
Rectangle
- x, y: int
- width, height: int
- color: Color
- borderStyle: Style
+ clone(): Shape
Circle
- x, y: int
- radius: int
- fillColor: Color
+ clone(): Shape
TextBox
- x, y: int
- text: String
- font: Font
- effects: List<Effect>
+ clone(): Shape
Canvas
- shapes: List<Shape>
+ duplicateShape(shape: Shape): Shape
+ addShape(shape: Shape): void
Implementation Strategy:

When a user selects a shape and presses duplicate, the Canvas calls shape.clone(). Each shape type implements cloning differently. Rectangle copies its dimensions and styling. TextBox performs a deep clone of its effects list because effects are mutable and shouldn't be shared between instances.

// In Canvas class
function duplicateShape(original: Shape):
  cloned = original.clone()
  cloned.setPosition(original.x + 10, original.y + 10)
  shapes.add(cloned)
  return cloned

// In TextBox class
function clone():
  newTextBox = new TextBox()
  newTextBox.text = this.text
  newTextBox.font = this.font // shallow (Font is immutable)
  newTextBox.effects = deepCloneList(this.effects)
  return newTextBox
Interview Tip: Mention offset positioning for clones so they don't appear exactly on top of the original. This shows you think about UX (User Experience), not just code structure.
Deep Copy Consideration:

The TextBox has a list of effects (shadows, glows, gradients). If we shallow copy the list, both original and clone share the same effect objects. Modifying an effect on the clone would affect the original. Therefore, we deep clone the effects list. However, if Font objects are immutable, shallow copying the font reference is safe and efficient.

💡 Key Takeaways
Each shape implements its own cloning logic based on its attributes
Canvas doesn't need to know concrete shape types to duplicate them
Deep cloning is used for mutable nested objects like effect lists
Immutable objects like Font can be shallow copied safely
Cloned shapes are offset slightly to avoid overlapping the original
📌 Examples
1Duplicating styled rectangles in Figma
2Copying text boxes with multiple effects in Canva
3Cloning configured UI components in Notion
← Back to Prototype Pattern Overview