13.4.2022 |

Observer

The Observer Pattern is a behavioral pattern. The pattern mainly consists of two components. An observable subject and a Subscriber, who is notified if the subject is changed. This prevents unnecessary polling and achieves loose coupling between the involved objects.

ObserverPattern Quelle: https://refactoring.guru/design-patterns/observer

Multiple Examples in Java:

Classic implementation:

public class LazyProgrammer {
    private long hoursOfNetflix;

    private final List<Authority> authorities = new ArrayList<>();

    public void addChef(Chef chef) {
        this.authorities.add(chef);
    }

    public void watchNetflix(long hoursOfNetflix) {
        this.hoursOfNetflix += hoursOfNetflix;
        authorities.forEach(authority -> authority.update(hoursOfNetflix));
    }
}

public class Chef implements Authority {
    private long trackedHoursOfNetflix;

    @Override
    public void update(long hoursOfNetflixUse) {
        this.trackedHoursOfNetflix = hoursOfNetflixUse;
    }
}

public interface Authority {
    void update(long hours);
}

public static void main(String[] args) {
   observable.LazyProgrammer observable = new observable.LazyProgrammer();
   observable.Chef observer = new observable.Chef();

   observable.addChef(observer);
   observable.watchNetflix(5);

   assert(observable.getHoursOfNetflix() == observer.getTrackedHoursOfNetflix());
}

Example Implementation With Java Flow API:

public class LazyProgrammer extends SubmissionPublisher<Long> {
    private long hours;

    public void watchNetflix(long hours) {
        this.hours += hours;
        this.submit(hours);
    }
}

public class Chef implements Flow.Subscriber<Long> {
        private Flow.Subscription subscription;
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            System.out.println("Subscribed");
            this.subscription = subscription;
            this.subscription.request(1);
        }
        @Override
        public void onNext(Long item) {
            subscription.request(1);
        }
        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
        }
        @Override
        public void onComplete() {
            System.out.println("Done");
        }
}

public static void main(String[] args) throws InterruptedException {
    flowapi.Chef chef = new flowapi.Chef();
    flowapi.LazyProgrammer lazyProgrammer = new flowapi.LazyProgrammer();

    lazyProgrammer.subscribe(chef);

    lazyProgrammer.watchNetflix(5);
    lazyProgrammer.watchNetflix(6);

    lazyProgrammer.close();
    Thread.sleep(1000);

    assert(lazyProgrammer.getHours() == chef.getTrackedHoursOfNetflix());
}
Michael Virks
Zur Übersicht

Mehr vom DevSquad...

Jörg Herbst

Wie SQL funktioniert

Jörg Herbst

Speedtest des Netzwerks unter MacOS