Skip to content

Commit 6755b2b

Browse files
author
samuel.casanova
committedMay 5, 2023
add prototype design pattern real world example
1 parent bcce5af commit 6755b2b

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
 

‎src/Prototype/RealWorld/index.ts

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/**
2+
* EN: Real World Example for the Prototype design pattern
3+
*
4+
* Need: To have a Document class with several components that can be copied & pasted
5+
*
6+
* Solution: All components should have the ability to clone themselves
7+
*/
8+
9+
/**
10+
* EN: The component extends the Cloneable interface
11+
*
12+
*/
13+
export interface Cloneable<T> {
14+
clone(): T;
15+
}
16+
17+
export class ComponentPrototype implements Cloneable<ComponentPrototype> {
18+
clone(): ComponentPrototype {
19+
return { ...this };
20+
}
21+
}
22+
23+
/**
24+
* EN: The document class
25+
*
26+
*/
27+
export class Document extends ComponentPrototype {
28+
components: ComponentPrototype[] = [];
29+
30+
clone(): Document {
31+
const clonedDocument = new Document();
32+
clonedDocument.components = this.components.map(c => c.clone());
33+
return clonedDocument;
34+
}
35+
36+
add(component: ComponentPrototype) {
37+
this.components.push(component);
38+
}
39+
}
40+
41+
/**
42+
* EN: Some components to add to a document
43+
*
44+
*/
45+
export class Title extends ComponentPrototype {
46+
constructor(public text: string) {
47+
super();
48+
}
49+
50+
setText(text: string) {
51+
this.text = text;
52+
}
53+
}
54+
55+
export class Drawing extends ComponentPrototype {
56+
constructor(public shape: 'circle' | 'square' | 'line') {
57+
super();
58+
}
59+
60+
setShape(shape: 'circle' | 'square' | 'line') {
61+
this.shape = shape;
62+
}
63+
}
64+
65+
export class TextBox extends ComponentPrototype {
66+
constructor(public text: string) {
67+
super();
68+
}
69+
70+
setText(text: string) {
71+
this.text = text;
72+
}
73+
}
74+
75+
export class Link extends ComponentPrototype {
76+
constructor(public text: string, public url: string) {
77+
super();
78+
}
79+
80+
setText(text: string) {
81+
this.text = text;
82+
}
83+
84+
setUrl(url: string) {
85+
this.url = url;
86+
}
87+
}
88+
89+
/**
90+
* EN: The client code.
91+
*
92+
*/
93+
const document = new Document();
94+
const title = new Title('Example Domain');
95+
const textbox = new TextBox('This domain is for use in illustrative examples');
96+
document.add(title);
97+
document.add(new Drawing('line'));
98+
document.add(textbox);
99+
document.add(new Link('example.com', 'https://example.com/'));
100+
101+
const clonedDocument = document.clone();
102+
103+
title.setText('New title for the original document');
104+
textbox.setText('New textbox text for the original document');
105+
106+
console.log('document is:');
107+
console.log(document);
108+
console.log('clonedDocument is:');
109+
console.log(clonedDocument);

0 commit comments

Comments
 (0)