Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
- */
- //https://medium.com/@smagid_allThings/uml-class-diagrams-tutorial-step-by-step-520fd83b300b
- package com.mycompany.publishsubscribe;
- import java.util.*;
- /**
- *
- * @author IvoRakitin
- */
- public class PublishSubscribe {
- public static void main(String[] args) {
- Publisher publisher = new Publisher("p1");
- Subscriber s1 = new Subscriber("s1");
- s1.subscribe(publisher);
- Subscriber s2 = new Subscriber("s2");
- s2.subscribe(publisher);
- Subscriber s3 = new Subscriber("s3");
- s3.subscribe(publisher);
- publisher.doWork();
- s2.unsubscribe(publisher);
- System.out.println();
- publisher.doWork();
- /*
- int numSubs = 10;
- Publisher p1 = new Publisher("p1");
- Publisher p2 = new Publisher("p2");
- Subscriber[] s = new Subscriber[numSubs];
- for (int i = 0; i < s.length; i++) {
- s[i] = new Subscriber("s" + i);
- s[i].subscribe(p1);
- if (i % 2 == 0)
- s[i].subscribe(p2);
- }
- p1.doWork();
- p2.doWork();
- for (int i = 0; i < s.length; i++) {
- if (i % 2 != 0)
- s[i].unsubscribe(p1);
- }
- System.out.println("");
- p1.doWork();
- p2.doWork(); */
- }
- }
- class Publisher {
- private List<Calling> subscribers;
- private String name;
- public Publisher(String name) {
- subscribers = new ArrayList<>();
- this.name = name;
- }
- public interface Calling {
- public void call(Object state, String n);
- }
- public void subscribe(Calling sub) {
- subscribers.add(sub);
- }
- public void unsubscribe(Calling subscriber) {
- subscribers.remove(subscriber);
- }
- public void doWork() {
- for (int i = 0; i < 100; i++) {
- if (i == 50) {
- for (Calling subscriber : subscribers) {
- subscriber.call(i, name);
- }
- }
- }
- }
- }
- class Subscriber {
- private String name;
- private Publisher.Calling calling;
- public Subscriber(String name) {
- this.name = name;
- }
- public void subscribe(Publisher publisher) {
- if (calling == null) {
- /*
- calling = (Object state) -> {
- stateChanged(state);
- };*/
- calling = new Publisher.Calling() {
- @Override
- public void call(Object state, String n) {
- stateChanged(state, n);
- }
- };
- }
- publisher.subscribe(calling);
- }
- public void unsubscribe(Publisher publisher) {
- if (calling != null) {
- publisher.unsubscribe(calling);
- }
- }
- private void stateChanged(Object state, String n) {
- System.out.println("Subscriber " + name + " called with state " + state + " from Publisher " + n);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement