Observer pattern/Java implementation with code/

Source: Internet
Author: User

/Note: Scenarios and examples refer to design patterns on GitHub. Portal: Https://github.com/iluwatar/java-design-patterns/tree/master/observer

Scene:

A weather forecast system, which subscribes to the weather forecast, sends the notice to all those who subscribe to the weather forecast when the weather changes. As the Orc (Orcs) and the Hobitts subscribed to the weather forecast system, the orcs and the Hobbits received notice of the weather turning rainy when the weather changed from sunny to rainy. If there are other people (Terran) who have subscribed to the weather forecast, simply add the Terran Subscriber to the weatherobserver so that when the weather changes, the Terran will receive a weather notice.

Intention:

Defines a one-to-many relationship between objects that automatically notifies and updates all dependents when a state change occurs for an object.

Specific implementation:

subscribers to the weather forecast system, such as Orcs and Hobitts, abstracted the subscribers to the weather forecast as interfaces (Weatherobserver), and all the people who subscribed to the weather forecast had to implement the interface. Also in the Weather Class (Weather) you have to open an interface for them to subscribe to, such as using list<subscriber> observers and writing a method Addobserver (Weatherobserver obs) to get them to subscribe, Once the weather changes, notify all subscribing to the Weather Method Notifyallobserver ().

Talk is cheap,show me the code ......................................................................................................................... ......................................................................................................................... .......... (Split line)

Define the weather type (Weathertype.java), defined as the enumeration type (Sunny,rainny,windy,clod)

public enum Weathertype {     sunny,windy,clod,rainy;  @Override public String toString () {return this.name (). toLowerCase ();}}

The subscriber is then abstracted into an interface (Weatherobserver.java), and all subscriptions to the weather forecast system must implement this interface.

 Public Interface Weatherobserver {      publicvoid  upadate (Weathertype currentweather);

The Weather Class (Weather) is responsible for defining the data structure to receive subscribers and notify the update subscribers of weather changes. Use List<weatherobserver> to receive Subscribers, define method Addobserver to receive new subscribers and Notifyallobsever methods to update subscribers ' weather status.

Importjava.util.ArrayList;Importjava.util.List; Public classWeather {PrivateWeathertype Currentweather; PrivateList<weatherobserver>observers;  PublicWeather () {observers=NewArraylist<>(); Currentweather=Weathertype.sunny; }           Public voidAddobservers (Weatherobserver observer) {OBSERVERS.ADD (Observer); }           Public voidRemoveobservers (Weatherobserver observer) {OBSERVERS.REMOVE (Observer); }                Public  voidtimepasses () {weathertype[] enumvalues=weathertype.values (); /*For (Weathertype type:enumvalues) {System.out.println (type); }*/         //Change the weather and let the enum type of the weather push backwardscurrentweather=enumvalues[(currentweather.ordinal () + 1)%Enumvalues.length]; System.out.println ("The weather change to" +currentweather);     Notifyallobserver (); }           Public voidNotifyallobserver () { for(Weatherobserver obs:observers) {obs.         Upadate (Currentweather); }     }}

Add two subscriptions "people" of the weather Forecast, an orc (Orcs.java) a Hobbit (Hobitts.java). As stated above, the Weatheroberver interface must be implemented to subscribe to the weather forecast.

 Public classOrcsImplementsweatherobserver{@Override Public voidupadate (Weathertype currentweather) {Switch(currentweather) { CaseCLOD:System.out.println ("The Orcs is freezing cold");  Break;  CaseSUNNY:System.out.println ("The Sun Hurts the Orcs ' eyes.");  Break;  CaseRAINY:System.out.println ("The orcs is dripping wet.");  Break;  CaseWINDY:System.out.println ("The orc smell almost vanishes in the wind."); default:             Break; }            } Public classHobbitsImplementsweatherobserver{@Override Public voidupadate (Weathertype currentweather) {Switch(currentweather) { CaseCLOD:System.out.println ("The hobbits is freezing cold");  Break;  CaseSUNNY:System.out.println ("The sun hurts the hobbits ' eyes.");  Break;  CaseRAINY:System.out.println ("The hobbits is dripping wet.");  Break;  CaseWINDY:System.out.println ("The hobbits smell almost vanishes in the wind."); default:             Break; }           }}

Write a main class to test the change function (App.java)

 Public classAPP { Public Static voidMain (string[] args) {Weather Weather=NewWeather (); Weather.addobservers (NewOrcs ()); Weather.addobservers (Newhobbits ()); Weather.addobservers (NewTerran ());                Weather.timepasses (); //weather.timepasses ();            }}

Output: (That is, when the weather changed from sunny to windy, orcs and Hobitts, who subscribed to the weather, received notice of the change in weather)

The weather  windythe orc smell almost vanishes in the wind. The hobbits smell almost vanishes in the wind.
use the Observer pattern in any of the following situations:
    • there are two aspects of abstraction, one dependent on the other. encapsulating These aspects in separate objects allows you to change and reuse them independently
    • You don't know how many objects you need to change when you change an object to change other objects
    • when an object should be able to notify other objects, it is not necessary to assume who the objects are. In other words, you don't want these objects to be tightly bound

Observer pattern/Java implementation with code/

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.