Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- class Subject<Tp> {
- private Tp state;
- private List<Observer> observers;
- public Subject() {
- observers = new ArrayList<>();
- }
- public Tp getState() {
- return state;
- }
- public void setState(Tp state) {
- this.state = state;
- notifyAllObs();
- }
- public void registerObs(Observer observer) {
- observers.add(observer);
- }
- private void notifyAllObs() {
- for (Observer observer : observers) {
- observer.update();
- }
- }
- }
- abstract class Observer {
- public Observer(Subject subject) {
- this.subject = subject;
- this.subject.registerObs(this);
- }
- protected Subject subject;
- public abstract void update();
- }
- //end obs pattern
- class Message {
- public String to, title, content;
- public Message(String to, String title, String content) {
- this.to = to;
- this.title = title;
- this.content = content;
- }
- @Override
- public String toString() {
- return "Message{" +
- "to='" + to + '\'' +
- ", title='" + title + '\'' +
- ", content='" + content + '\'' +
- '}';
- }
- }
- class MailObserver extends Observer {
- public MailObserver(Subject subject) {
- super(subject);
- }
- @Override
- public void update() {
- System.out.println("Mail sent! " + subject.getState().toString());
- }
- }
- class SmsObserver extends Observer {
- public SmsObserver(Subject subject) {
- super(subject);
- }
- @Override
- public void update() {
- System.out.println("Sms sent! " + subject.getState().toString());
- }
- }//*/
- public class Main {
- public static void main(String[] args) {
- var subject = new Subject<Message>();
- new MailObserver(subject);
- new SmsObserver(subject);
- subject.setState(new Message("andrew", "hi", "wyd?"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement