-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44.DesignADependencyInjectionCounter.java
More file actions
71 lines (55 loc) · 2.25 KB
/
44.DesignADependencyInjectionCounter.java
File metadata and controls
71 lines (55 loc) · 2.25 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
/* --------------------------------------------------------------------------
Dependency Injection Counter - Single File Java Demo
(LLD Compliant + Line-by-Line Explanation)
-------------------------------------------------------------------------- */
interface IStorage {
int getValue(); // gets current stored value
void setValue(int v); // sets updated value
}
/* --------------------------------------------------------------------------
In-Memory Storage implementing IStorage
-------------------------------------------------------------------------- */
class InMemoryStorage implements IStorage {
private int val; // stores counter value
public InMemoryStorage() {
this.val = 0; // initialize storage with zero
}
@Override
public int getValue() {
return this.val; // return stored number
}
@Override
public void setValue(int v) {
this.val = v; // update stored number
}
}
/* --------------------------------------------------------------------------
Counter class depends on IStorage (Dependency Injection)
-------------------------------------------------------------------------- */
class Counter {
private final IStorage storage; // reference to injected storage
public Counter(IStorage storage) {
this.storage = storage; // DI via constructor
}
public void increment() {
int current = storage.getValue(); // read value from storage
storage.setValue(current + 1); // write updated value back
}
public int value() {
return storage.getValue(); // return current value from storage
}
}
/* --------------------------------------------------------------------------
MAIN DEMO (Everything running in a single file)
-------------------------------------------------------------------------- */
public class Main {
public static void main(String[] args) {
IStorage storage = new InMemoryStorage(); // Dependency Injection
Counter counter = new Counter(storage); // Injected into Counter
counter.increment(); // +1
counter.increment(); // +1
counter.increment(); // +1
System.out.println("Final Counter Value: " + counter.value());
// Expected Output: 3
}
}