-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDIExample.java
More file actions
39 lines (29 loc) · 1010 Bytes
/
Copy pathDIExample.java
File metadata and controls
39 lines (29 loc) · 1010 Bytes
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
/**
* Day 37 - Dependency Injection: Constructor Injection
*/
public class DIExample {
interface EmailService {
void sendEmail(String to, String message);
}
static class GmailService implements EmailService {
public void sendEmail(String to, String message) {
System.out.println("Sending via Gmail to " + to + ": " + message);
}
}
static class UserService {
private EmailService emailService;
// Constructor Injection
UserService(EmailService emailService) {
this.emailService = emailService;
}
void registerUser(String email) {
emailService.sendEmail(email, "Welcome!");
}
}
public static void main(String[] args) {
System.out.println("=== Dependency Injection ===\n");
EmailService emailService = new GmailService();
UserService userService = new UserService(emailService);
userService.registerUser("john@example.com");
}
}