Professional Documents
Culture Documents
A TYPICAL EXAMPLE
Let us take a real-life implementation of the Observer Design
Pattern. A newsletter with sales and new products of the shop is the
subject. All the subscribers in this newsletter are observers.
Every time a new product is added to the shop, the marketing sends
a newsletter. It might include media, such as video and photos of
the product. The subscribers are notified about the new product.
In this example, the subscribers are observers, and the store is the
subject.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Moving ahead and implement the Observer design pattern using
java. Java provides an in-built platform for implementing the
Observer pattern through java. util.Observable class and java.
util.Observer interface.
IMPLEMENTATION
Let us implement an observer design pattern with the Shop
Newsletter example. Subscribers can register themselves to get
updates on any news of the Shop. In the same way, they can
unsubscribe if they have no interest anymore. Subscribers are
acting as Observers, and Store will act as a Subject.
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
In this example, the store is the Subject. It contains a list of
observers, which are all subscriptions to the news of the store.
import java.util.ArrayList;
import java.util.List;
@Override
public void notifySubscribers(String n) {
observers.forEach(observer -> observer.notification(news,
n));
}
}
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
protected String name;
public Subscriber(String name) {
super();
this.name = name;
}
@Override
public void notification(String handle, String news) {
System.out.printf("%s received news: %s - NEWS:
'%s'\n",name, handle, news);
}
}
In Console:
Keep coding…
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com