Skip to content

Commit 3de4c77

Browse files
authored
Factory Design Pattern
Factory Design Pattern in Java
1 parent de3e590 commit 3de4c77

6 files changed

+42
-0
lines changed

EmailNotification.java

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
public class EmailNotification implements Notification {
2+
public void notifyUser() {
3+
System.out.println("Email notif");
4+
}
5+
}

Notification.java

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
public interface Notification {
2+
void notifyUser();
3+
}

NotificationFactory.java

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class NotificationFactory {
2+
Notification createNotification(String type) {
3+
switch (type) {
4+
case "SMS":
5+
return new SMSNotification();
6+
case "Email":
7+
return new EmailNotification();
8+
case "Push":
9+
return new PushNotification();
10+
}
11+
return null;
12+
}
13+
}

PushNotification.java

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
public class PushNotification implements Notification {
2+
public void notifyUser() {
3+
System.out.println("Push notif");
4+
}
5+
}

SMSNotification.java

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
public class SMSNotification implements Notification {
2+
public void notifyUser(){
3+
System.out.println("SMS notif");
4+
}
5+
}

Test.java

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class Test {
2+
public static void main(String[] args) {
3+
NotificationFactory nf = new NotificationFactory();
4+
Notification sms = nf.createNotification("SMS");
5+
Notification email = nf.createNotification("Email");
6+
Notification push = nf.createNotification("Push");
7+
sms.notifyUser();
8+
email.notifyUser();
9+
push.notifyUser();
10+
}
11+
}

0 commit comments

Comments
 (0)