Head First (ii)--viewer (Observer) mode

Source: Internet
Author: User


There is a pattern to help your audience know the status quo, not to miss the object of interest. Objects even at run time can decide whether to continue being notified. The Observer pattern is one of the most used patterns in the JDK and is useful.



Publisher + Subscriber = Observer mode



If you know what a newspaper's subscription is about, you know what the observer pattern is, but the name is not the same: the publisher is renamed "Subject (Subject)" and the Subscriber is renamed "Observer (Observer)".



The Observer pattern defines a one-to-many dependency between objects, so that when an object changes state, all its dependents are notified and updated automatically.



There is more than one way to implement the observer pattern, but it is most common to design classes that contain subject and observer interfaces.



The subject only knows that the observer implements an interface (that is, the Observer interface). The topic does not need to know who the observer is, what it does, or other details.



If we have a new concrete class that needs to be an observer, we don't need to modify the code of the subject in order to be compatible with the new type, all we have to do is implement this observer interface in the new class and register as an observer. The topic does not care about anything else, it only sends notifications to all objects that implement the Observer interface.



When two objects are loosely coupled, they can still interact, but are less aware of each other's details.



Design Principle : Strive for the design of loose coupling between interacting objects.



Java provides built-in support for observer patterns. While there are some times when you can take advantage of the built-in support of Java, many times, your own creator will be more resilient.



Observer pattern structure diagram







The following roles are in the Observer pattern:
Subject: Abstract subject (abstract observer), abstract theme characters save all observer objects in a collection, each subject can have any number of observers, abstract topics provide an interface that can add and remove observer objects. ConcreteSubject: A specific topic (a specific observer), which stores the state of a specific observer object and sends a notification to all registered observers when the internal state of a specific topic changes. Observer: Abstract Observer, an abstract class of observers, defines an update interface that updates itself when a topic change notification is received. Concrereobserver: A specific observer that implements an updated interface defined by an abstract observer to update its state when a topic change notification is obtained.






Simple Implementation



For example, our users, to subscribe to the weather SMS.



Abstract Observer (Observer)
An updated method is defined inside:






Public interface Observer {
	void update (String msg);
}
Specific Observer (Concrereobserver)
The user is the observer, which implements the updated method:

public class User implements Observer {

	private String name;

	Public User (String name) {
		this.name = name;
	}
	
	@Override public
	void Update (String msg) {
		System.out.println ("I am:" + name + ", received message:" + msg);
	}
}
Abstract Observer (Subject)
Abstract topic, provides three methods of attach, Detach, notify:

Public interface Subject {
	/**
	 * Add subscribers
	 *
	 * @param observer *
	/VOID attach (Observer observer); c6/>/**
	 * Delete subscribers
	 *
	 * @param observer *
	/VOID Detach (Observer observer);

	/**
	 * Notify subscribers
	 *
	 * @param msg *
	/void Notify (String msg);
}
Specific observed (ConcreteSubject)
A weather station is a specific subject (a specific observer) that stores the users who subscribe to the weather forecast and implements the methods in the abstract topic:

public class Weatherstation implements Subject {

	//Store subscription weather user
	private list<observer> observers = new Arraylist<> ();

	@Override public
	void Attach (Observer Observer) {
		observers.add (Observer);
	}

	@Override public
	void Detach (Observer Observer) {
		observers.remove (Observer);
	}

	@Override public
	void Notify (String msg) {for
		(Observer observer:observers) {
			observer.update (msg); c33/>}}}
Client Calls








public class Client {public
	static void Main (string[] args) {

		user User0 = new User ("Dapeng");
		User User1 = new User ("Little Shenyang");
		User User2 = New User ("Yu Yunpeng");
		User User3 = New User ("Song");

		Weatherstation weatherstation = new Weatherstation ();
		Weatherstation.attach (USER0);
		Weatherstation.attach (user1);
		Weatherstation.attach (user2);
		Weatherstation.attach (USER3);

		Weatherstation.notify ("It's going to snow Tomorrow");}







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.