Sitemap
Design Pattern — Prototype in Angular

Design Pattern — Prototype in Angular

Design Pattern — Prototype in Angular

4 min readApr 1, 2025

--

Press enter or click to view image in full size
Image generated by Copilot AI

Creational Design Pattern are concerned with the way of creating objects.

In JavaScript, TypeScript, etc., the way to create an object is by using the new operator.

Creational patterns consist of:
1. Factory (Simple Factory)
2. Factory Method
3. Abstract Factory
4. Singleton
5. Prototype
6. Builder
7. Object Pool

In this article, I will explain how the Prototype design pattern works. You can see and run an example of the Prototype pattern in a demo project, which can be found at this link here.

The Prototype design pattern delegates the cloning process to objects that need it. By defining a common interface for all objects that use cloning. This interface lets you clone an object without coupling your code to the class of that object.

Copying objects can be useful for many functionalities for example test data, comparing a copy od an object with another object,editing a copy before confirming the save of the original object and many others.

Get Bulicka Ola’s stories in your inbox

Join Medium for free to get updates from this writer.

I will present an example of a user data form. Absolutely, the example may be different. The user enters data into the form. Then clicks the Copy User button. The form code with the cloneUser() method that copies the user object is below:

import { Component, inject } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { Address, User } from './prototype';


@Component({
selector: 'app-prototype',
standalone: true,
imports: [ReactiveFormsModule],
template: `

<form [formGroup]="userForm">
<div>
<label for="name">Name:</label>
<input type="text" formControlName="name" id="name">
</div>
<div>
<label for="age">Age:</label>
<input type="number" formControlName="age" id="age">
</div>
<div>
<label for="city">City:</label>
<input type="text" formControlName="city" id="city">
</div>
<div>
<label for="street">Street:</label>
<input type="text" formControlName="street" id="street">
</div>

<button type="button" (click)="cloneUser()">Clone User</button>
</form>

@if (clonedUser) {
<h3>Cloned User</h3>
<p>Name: {{ clonedUser.getName() }}</p>
<p>Age: {{ clonedUser.getAge() }}</p>
<p>City: {{ clonedUser.getAddress().getCity() }}</p>
<p>Street: {{ clonedUser.getAddress().getStreet() }}</p>
}`,
styleUrl: './prototype.component.scss'
})
export class PrototypeComponent {

private formBuilder = inject(FormBuilder);
protected clonedUser!: User;
protected userForm: FormGroup = this.formBuilder.group({
name: [''],
age: [null],
city: [''],
street: [''],
});


cloneUser() {
const user = new User(
this.userForm.controls['name'].value,
this.userForm.controls['age'].value,
new Address(
this.userForm.controls['city'].value,
this.userForm.controls['street'].value));

this.clonedUser = user.clone();

if (user.getName() === this.clonedUser.getName()) {
console.info('Primitive field values have been carried over to a clone.');
} else {
console.info('Primitive field values have not been copied.');
}
}
}

The cloneUser() method implements the creation of the new User object. This class describes the user. The address parameter is an instance of the Address class. Both classes implement the Cloneable<T> interface containing the clone() method, which creates a new object of the class in which it is located. The method for the task of creating a copy ( in other words a clone). Below is the implementation of the copy/clone functionality:

export interface Cloneable<T> {
clone(): T;
}

export class Address implements Cloneable<Address> {
constructor(
private city: string,
private street: string) { }

clone(): Address {
return new Address(this.city, this.street);
}

getCity(): string {
return this.city;
}
setCity(city: string) {
this.city = city;
}

getStreet(): string {
return this.street;
}
setStreet(street: string) {
this.street = street;
}
}
export class User implements Cloneable<User> {
constructor(
private name: string,
private age: number,
private address: Address
) { }

clone(): User {
return new User(
this.name,
this.age,
this.address.clone()
);
}

getName(): string {
return this.name;
}
setName(name: string) {
this.name = name;
}

getAge(): number {
return this.age;
}
setAge(age: number) {
this.age = age;
}

getAddress(): Address {
return this.address;
}
setAddress(address: Address) {
this.address = address;
}
}

The following example implements changing the value of a copy/clone. However, the original value will not be changed because the copy/clone instance is at a different address in memory. It is a new object:

 const original = new Address("property initialization", "Street");
let clone = original.clone();

console.info(clone.getCity()); // "property initialization"
clone.setCity("change properties for copy/clone") ;
console.info(original.getCity()); // "property initialization"
console.info(clone.getCity()); // "change properties for copy/clone

The structure of the Prototype pattern consists of several elements:

  1. The Prototype interface declares the cloning methods. In our case, it is the Cloneable<T> interface.
  2. The Concrete Prototype class implements the cloning method. In addition to copying the original object’s data to the clone. In our case these are the User and Address classes.
  3. The Client creates a new object on which the copy/clone method is called. In our case, it is the PrototypeComponent component.

Summary

The Prototype pattern is used to create new objects based on existing instances instead of creating them from scratch using a constructor. It allows for object cloning, which can be useful when you want to retain an object’s properties and state but need a new instance. In JavaScript, there are other methods for copying objects. I analyzed this in more detail in the article “Copy — Best Practices — JavaScript and TypeScript”, link here.

Materials:

  1. Java. Wzorce projektowe. Translation: Piotr Badarycz. Original title: Java design patterns. A Tutorial. Author: James William Cooper
  2. https://refactoring.guru/design-patterns/prototype

--

--

Bulicka Ola
Bulicka Ola

Written by Bulicka Ola

I love working, analyzing, and discovering things I didn’t understand before, as well as exploring things I’m still trying to understand