Skip to content

Instantly share code, notes, and snippets.

@rohanjai777
Created November 8, 2022 20:26
Show Gist options
  • Save rohanjai777/be693d2bfb528c67d4d6f996d6b6c2fa to your computer and use it in GitHub Desktop.
Save rohanjai777/be693d2bfb528c67d4d6f996d6b6c2fa to your computer and use it in GitHub Desktop.
import java.util.*;
interface PaymentSuccessEventSubscriber{//has common method called notify
void notify(int order_id);
}
class EmailService implements PaymentSuccessEventSubscriber{
public void notify(int order_id){
sendEmail(order_id);
}
public void sendEmail(int order_id){
System.out.println("In email service");
}
}
class SmsService implements PaymentSuccessEventSubscriber{
public void notify(int order_id){
sendSms(order_id);
}
public void sendSms(int order_id){
System.out.println("In sms service");
}
}
//--------------------------
class Flipkart{
private List<PaymentSuccessEventSubscriber> subscribers = new ArrayList<>(); //list of subscribers
public void subscribe(PaymentSuccessEventSubscriber event){ //to add
subscribers.add(event);
}
public void unsubscribe(PaymentSuccessEventSubscriber event){ //to remove
subscribers.remove(event);
}
public void paymentSuccess(int order_id){ //when success call all the subscribers
for(PaymentSuccessEventSubscriber subscriber : subscribers){
subscriber.notify(order_id);
}
}
}
//---------------------------
public class Client{
//create event subscribers
private static PaymentSuccessEventSubscriber emailService = new EmailService();
private static PaymentSuccessEventSubscriber smsService = new SmsService();
public static void main(String[] args){
Flipkart flipkart = new Flipkart(); //make flipkart object
flipkart.subscribe(emailService); //add event subscribers
flipkart.subscribe(smsService);
flipkart.paymentSuccess(123); //on payment success, all subscribers gets called
flipkart.paymentSuccess(23);
}
}
//output
In email service
In sms service
In email service
In sms service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment