Repository navigation
Expand file tree
/
Copy path05-design-patterns.js
More file actions
78 lines (65 loc) · 2.34 KB
/
Copy path05-design-patterns.js
File metadata and controls
78 lines (65 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* 05 — COMMON DESIGN PATTERNS IN VANILLA JS
* -------------------------------------------
*/
// ── 1. Module pattern — encapsulate private state with a closure ────────
// Anything not returned stays private; only the returned object is public.
const Counter = (function () {
let count = 0; // private — inaccessible from outside
return {
increment() {
return ++count;
},
reset() {
count = 0;
},
};
})();
console.log(Counter.increment()); // 1
console.log(Counter.increment()); // 2
console.log(Counter.count); // undefined — truly private
// ── 2. Singleton — ensure only one instance ever exists ─────────────────
class Database {
static #instance; // private static field
constructor() {
if (Database.#instance) {
return Database.#instance; // return the existing instance instead of a new one
}
this.connection = `connected-${Date.now()}`;
Database.#instance = this;
}
}
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true — same instance every time
// ── 3. Factory — create objects without exposing `new`/constructor logic ─
function createUser(type, name) {
const base = { name, createdAt: Date.now() };
switch (type) {
case "admin":
return { ...base, role: "admin", permissions: ["read", "write", "delete"] };
case "guest":
return { ...base, role: "guest", permissions: ["read"] };
default:
return { ...base, role: "user", permissions: ["read", "write"] };
}
}
console.log(createUser("admin", "Abdul"));
console.log(createUser("guest", "Visitor"));
// ── 4. Observer — subscribe to and react to events ───────────────────────
class EventEmitter {
#listeners = {};
on(event, callback) {
(this.#listeners[event] ??= []).push(callback);
return this; // allow chaining
}
emit(event, ...args) {
(this.#listeners[event] ?? []).forEach((cb) => cb(...args));
}
}
const emitter = new EventEmitter();
emitter.on("login", (user) => console.log(`${user} logged in`));
emitter.on("login", (user) => console.log(`Sending welcome email to ${user}`));
emitter.emit("login", "Abdul");
// Both listeners fire independently — this decouples the "login" event
// from whatever code reacts to it.