Advertisement
STANAANDREY

observer example

Jan 15th, 2023
764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. class Subject<Tp> {
  5.     private Tp state;
  6.     private List<Observer> observers;
  7.  
  8.     public Subject() {
  9.         observers = new ArrayList<>();
  10.     }
  11.  
  12.     public Tp getState() {
  13.         return state;
  14.     }
  15.  
  16.     public void setState(Tp state) {
  17.         this.state = state;
  18.         notifyAllObs();
  19.     }
  20.  
  21.     public void registerObs(Observer observer) {
  22.         observers.add(observer);
  23.     }
  24.  
  25.     private void notifyAllObs() {
  26.         for (Observer observer : observers) {
  27.             observer.update();
  28.         }
  29.     }
  30. }
  31.  
  32. abstract class Observer {
  33.     public Observer(Subject subject) {
  34.         this.subject = subject;
  35.         this.subject.registerObs(this);
  36.     }
  37.  
  38.     protected Subject subject;
  39.     public abstract void update();
  40. }
  41. //end obs pattern
  42.  
  43. class Message {
  44.     public String to, title, content;
  45.  
  46.     public Message(String to, String title, String content) {
  47.         this.to = to;
  48.         this.title = title;
  49.         this.content = content;
  50.     }
  51.  
  52.     @Override
  53.     public String toString() {
  54.         return "Message{" +
  55.                 "to='" + to + '\'' +
  56.                 ", title='" + title + '\'' +
  57.                 ", content='" + content + '\'' +
  58.                 '}';
  59.     }
  60. }
  61.  
  62. class MailObserver extends Observer {
  63.  
  64.     public MailObserver(Subject subject) {
  65.         super(subject);
  66.     }
  67.  
  68.     @Override
  69.     public void update() {
  70.         System.out.println("Mail sent! " + subject.getState().toString());
  71.     }
  72. }
  73.  
  74. class SmsObserver extends Observer {
  75.  
  76.     public SmsObserver(Subject subject) {
  77.         super(subject);
  78.     }
  79.  
  80.     @Override
  81.     public void update() {
  82.         System.out.println("Sms sent! " + subject.getState().toString());
  83.     }
  84. }//*/
  85.  
  86. public class Main {
  87.  
  88.     public static void main(String[] args) {
  89.         var subject = new Subject<Message>();
  90.  
  91.         new MailObserver(subject);
  92.         new SmsObserver(subject);
  93.  
  94.         subject.setState(new Message("andrew", "hi", "wyd?"));
  95.     }
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement