Skip to content

Commit 89ee1c3

Browse files
Updated the README.md and added the Prototype Pattern docs
1 parent 1e8e3b6 commit 89ee1c3

7 files changed

Lines changed: 182 additions & 2 deletions

File tree

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
This repository is cloned from the [Quartz repository](https://github.com/jackyzha0/quartz) and has been modified according to our needs.
44

5+
6+
> [!IMPORTANT]
7+
> No Further Updates will be made in these website due to migration of these Website. In Future we are going to move from [Quartz](https://quartz.jzhao.xyz/) to [Astro](https://astro.build/) for more better SEO and migration Changes. But Contents or article regarding the Design patterns will be uploaded/posted.
8+
9+
510
## Running Locally
611

712
To run the website locally, use:
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,8 @@ Finally, remember that **design patterns are guidelines, not strict rules**. Rea
100100

101101
- [[Memento Pattern]] :
102102
**Trigger clue:** “Undo/Redo”, “Save and restore state”, “Checkpoint or Snapshot”
103-
**Core idea:** Capture and store an object's state so it can be restored later without exposing its internal implementation details.
103+
**Core idea:** Capture and store an object's state so it can be restored later without exposing its internal implementation details.
104+
105+
- [[Prototype Pattern]] :
106+
**Trigger clue:** “Create a copy”, “Clone an existing object”, “Many similar objects needed”
107+
**Core idea:** Create new objects by cloning an existing object instead of creating and initializing them from scratch.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,7 @@ The **Interpreter Pattern** is a behavioral design pattern that represents a lan
4646
**Mediator Pattern** is a behavioral design pattern that centralizes communication between objects through a mediator, so objects do not communicate with each other directly.
4747
### 21. Memento Pattern
4848
**Memento Pattern** is a behavioral design pattern that saves an object's state so it can be restored later without exposing its internal details.
49+
### 22. Prototype Pattern
50+
**Prototype Pattern** is a creational design pattern that creates new objects by cloning an existing object instead of creating them from scratch.
4951

5052
_more Coming soon_

content/Prototype Pattern.md

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
---
2+
title: Prototype Pattern
3+
created: 2026-06-13
4+
tags:
5+
- creational
6+
---
7+
## Definition
8+
9+
**Prototype Pattern** is a **creational** design pattern that creates new objects by copying (cloning) an existing object, instead of creating and initializing a new object from scratch. This is useful when object creation is expensive or when many similar objects are needed.
10+
11+
---
12+
## Real World Analogy
13+
14+
Imagine you have created a document containing 100 pages. Now you need another document that is almost identical to the first one. Creating the new document from scratch would require typing all 100 pages again, which is both time-consuming and unnecessary.
15+
16+
A better approach is to make a copy of the existing document and then modify only the parts that need to be different. The original document acts as a prototype, and the copied document becomes a new object created from that prototype.
17+
18+
The same idea applies to software development. Instead of repeatedly creating and configuring similar objects from scratch, we create one fully configured object and then clone it whenever needed.
19+
20+
Another good example comes from the gaming industry. Consider a game that contains hundreds of soldier characters. Creating a character may involve loading models, textures, animations, weapons, movement logic, and other assets. Loading these assets repeatedly for every character would be expensive.
21+
22+
Instead, the game creates one fully initialized soldier, loads all the required assets, and then clones that soldier multiple times. Each cloned soldier can then be customized with small changes such as a different weapon, health value, or appearance.
23+
24+
This approach reduces initialization overhead, improves performance, and avoids repeating the same setup process again and again.
25+
26+
This is exactly where the Prototype Pattern becomes useful.
27+
28+
---
29+
## Design
30+
31+
```mermaid
32+
classDiagram
33+
34+
class Prototype {
35+
<<interface>>
36+
+clone() : Prototype
37+
}
38+
39+
class GameCharacter {
40+
-characterType : String
41+
-health : int
42+
-weapon : String
43+
44+
+GameCharacter(characterType : String, health : int, weapon : String)
45+
+setWeapon(weapon : String) : void
46+
+display() : void
47+
+clone() : Prototype
48+
}
49+
50+
class Client
51+
52+
Prototype <|.. GameCharacter : implements
53+
Client ..> GameCharacter : creates & clones
54+
```
55+
In this design:
56+
- `Prototype` defines the cloning contract.
57+
- `GameCharacter` is the concrete prototype that knows how to create its own copy.
58+
- `Client` creates an object and requests clones whenever new objects are required.
59+
---
60+
## Implementation in Java
61+
```java title="Prototype.java"
62+
// Prototype Pattern which can Supports the Cloning
63+
interface Prototype {
64+
public Prototype clone();
65+
}
66+
```
67+
68+
The `Prototype` interface defines a single method called `clone()`. Any class that wants to support cloning must implement this interface and provide its own cloning logic.
69+
```java title="GameCharacter.java"
70+
// Game Character
71+
class GameCharacter implements Prototype {
72+
private String characterType;
73+
private int health;
74+
private String weapon;
75+
76+
public GameCharacter(String characterType, int health, String weapon) {
77+
this.characterType = characterType;
78+
this.health = health;
79+
this.weapon = weapon;
80+
}
81+
82+
public void setWeapon(String weapon) {
83+
this.weapon = weapon;
84+
}
85+
86+
public void display() {
87+
System.out.printf("Character=%s,Health=%d,Weapon=%s\n",
88+
this.characterType,
89+
this.health,
90+
this.weapon);
91+
}
92+
93+
@Override
94+
public Prototype clone() {
95+
return new GameCharacter(
96+
this.characterType,
97+
this.health,
98+
this.weapon
99+
);
100+
}
101+
}
102+
```
103+
`GameCharacter` represents the object that can be cloned.
104+
105+
The constructor initializes the character's state. The `setWeapon()` method allows us to modify a cloned object after it has been created.
106+
107+
The most important method is `clone()`. Instead of asking the client to create a new character manually, the object creates a copy of itself and returns it.
108+
109+
This is the core idea behind the Prototype Pattern.
110+
```java title="PrototypePattern.java"
111+
public static void main(String[] args) {
112+
113+
// Soldier Character
114+
GameCharacter soldier =
115+
new GameCharacter("Soldier", 100, "Gun");
116+
117+
// Soldier 2 Character
118+
GameCharacter soldier2 =
119+
(GameCharacter) soldier.clone();
120+
121+
// Customize the clone
122+
soldier2.setWeapon("Pistol");
123+
124+
soldier.display();
125+
soldier2.display();
126+
127+
// Address
128+
System.out.println(soldier.hashCode());
129+
System.out.println(soldier2.hashCode());
130+
}
131+
```
132+
First, we create a soldier character.
133+
Instead of creating another soldier using the constructor, we create a copy by calling the `clone()` method.
134+
After cloning, we change the weapon of the second soldier from `Gun` to `Pistol`.
135+
Finally, we display both objects and print their hash codes. Different hash codes indicate that both objects are separate instances in memory even though one was created from the other.
136+
137+
**Output:**
138+
```bash
139+
Character=Soldier,Health=100,Weapon=Gun
140+
Character=Soldier,Health=100,Weapon=Pistol
141+
1721931908
142+
1198108795
143+
```
144+
The output shows that changing the cloned object does not affect the original object.
145+
The original soldier still has a `Gun`, while the cloned soldier uses a `Pistol`.
146+
147+
---
148+
## Real World Examples
149+
1. **Java Collections (`ArrayList.clone()`)**
150+
Java's `ArrayList` provides a `clone()` method that creates a copy of an existing list instead of building a new one manually.
151+
2. **.NET `MemberwiseClone()`**
152+
The .NET framework provides `MemberwiseClone()` to create a shallow copy of an object, which follows the Prototype Pattern.
153+
3. **Document Templates (Microsoft Word, LibreOffice)**
154+
When you create a new resume, invoice, or report from a template, the application creates a copy of the template and lets you customize it.
155+
4. **Game Engines (Unity, Unreal Engine)**
156+
Game engines often duplicate existing game objects, NPCs, enemies, or prefabs instead of creating each object from scratch.
157+
---
158+
## Design Principles:
159+
160+
- **Encapsulate What Varies** - Identify the parts of the code that are going to change and encapsulate them into separate class just like the Strategy Pattern.
161+
- **Favor Composition Over Inheritance** - Instead of using inheritance on extending functionality, rather use composition by delegating behavior to other objects.
162+
- **Program to Interface not Implementations** - Write code that depends on Abstractions or Interfaces rather than Concrete Classes.
163+
- **Strive for Loosely coupled design between objects that interact** - When implementing a class, avoid tightly coupled classes. Instead, use loosely coupled objects by leveraging abstractions and interfaces. This approach ensures that the class does not heavily depend on other classes.
164+
- **Classes Should be Open for Extension But closed for Modification** - Design your classes so you can extend their behavior without altering their existing, stable code.
165+
- **Depend on Abstractions, Do not depend on concrete class** - Rely on interfaces or abstract types instead of concrete classes so you can swap implementations without altering client code.
166+
- **Talk Only To Your Friends** - An object may only call methods on itself, its direct components, parameters passed in, or objects it creates.
167+
- **Don't call us, we'll call you** - This means the framework controls the flow of execution, not the user’s code (Inversion of Control).
168+
- **A class should have only one reason to change** - This emphasizes the Single Responsibility Principle, ensuring each class focuses on just one functionality.
File renamed without changes.
File renamed without changes.

content/index.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,8 @@ Consider an `SQLManager` class that performs CRUD operations. It has an `ILogger
147147
22. [[Interpreter Pattern]]
148148
23. [[Mediator Pattern]]
149149
24. [[Memento Pattern]]
150-
25. [[Glossary]]
150+
25. [[Prototype Pattern]]
151+
26. [[Glossary]]
151152

152153
---
153154
> [!Note]

0 commit comments

Comments
 (0)