The observer pattern for Java design patterns

Source: Internet
Author: User

Tag: Java logs this dependent for Code mode pack

The observer pattern for Java design patterns

Have always wanted to write a study of the Observer Pattern Summary no opportunity, today learning to block the principle of the queue to see in the implementation of the producer consumer when the notification mode, is the so-called observer mode, just by the way to tidy up a bit.

1. Introduction

The Observer pattern defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated. That is, the publish-subscribe mode.

The observer pattern involves the following participants:

    • Subject (target): the interface of the Observer, providing methods for registering/deleting observers and sending notifications;
    • OBSERVER (Observer): observe the object interface of the target and provide a method to deal with the update when the target changes;
    • ConcreteSubject (target): the specific observer class that implements the Observer interface, maintains a reference to an observer, and invokes an update method of the observer at the time of notification;
    • Concreteobserver (Specific observer): the specific observer class that implements the Observer interface.
Usage scenarios for observer patterns
    • For example, if you have a Twitter focus on a person, the tweets posted by this person will be sent to you.
    • For example, if you follow a public number, this public post will be pushed to you.
2. Instance Code

Take Weibo attention to give an example, some people focus on a big V, then the Big V every time the micro-BO, these people will receive push, which the huge V-tweet let some people uncomfortable, decisive take off, then will not receive the Big V push message.

New Subject Interface
package con.wangjun.designPattern.observer;publicinterface Subject {    publicvoidaddFans(Observer o);  // 添加粉丝    publicvoidremoveFans(Observer o);  // 移除粉丝    publicvoidnotifyFans(String str);  // 通知粉丝}
New Observer Interface
package con.wangjun.designPattern.observer;publicinterface Observer {    // 当被观察者调用notifyFans发通知,update方法会被回调    publicvoidupdate(String str);}
New Subject Implementation Class
Package Con.wangjun.designPattern.observer;import java.util.ArrayList;import java.util.List; Public classVsubjectImplementsSubject {list<observer> List =NewArraylist<> ();//Post Weibo     Public void Publish(String str) {System. out.println("Big V released micro-blog:"+ str);//Notify All fans        Notifyfans(str); }@Override     Public void Addfans(Observer o) {list.Add(o); }@Override     Public void Removefans(Observer o) {list.Remove(o); }@Override     Public void Notifyfans(String str) { for(inti =0; I < list.size(); i++) {list.Get(i).Update(str); }    }}
New Observer Implementation Class
package con.wangjun.designPattern.observer;publicclassimplements Observer {        private String name;        publicFansObserver(String name) {        this.name = name;    }    @Override    publicvoidupdate(String str) {        System.out.println" 收到大V的微博发文:" + str);    }}
New Test class
Package Con.wangjun.designPattern.observer;import java.util.ArrayList;import java.util.List; Public classMain { Public Static void Main(string[] args) {Vsubject vs =New Vsubject();example of//large VList<fansobserver> fans =NewArraylist<> ();//Store all fans                 for(inti =0; I <5; i++) {Fansobserver F =New Fansobserver("Name"+ (i +1)); Fans.Add(f); Vs.Addfans(f); }//This tweet, 5 fans have received pushVs.Publish("My girlfriend is so nice!" ");//Incredibly show love, the first 2 fans, can not look down, take off!          for(inti =0; I <2; i++) {vs.Removefans(fans.)Get(i)); }//This time the Micro Bo, those two take off the person will not seeVs.Publish("I want to send all my fans an iphone X"); }}
Run results
大V发布微博:我的女朋友真好看!name1 收到大V的微博发文:我的女朋友真好看!name2 收到大V的微博发文:我的女朋友真好看!name3 收到大V的微博发文:我的女朋友真好看!name4 收到大V的微博发文:我的女朋友真好看!name5 收到大V的微博发文:我的女朋友真好看!大V发布微博:我要送所有粉丝一部iPhone Xname3 收到大V的微博发文:我要送所有粉丝一部iPhone Xname4 收到大V的微博发文:我要送所有粉丝一部iPhone Xname5 收到大V的微博发文:我要送所有粉丝一部iPhone X

Reference:

"Object-oriented design pattern"

The observer pattern for Java design Patterns https://www.cnblogs.com/luohanguo/p/7825656.html

The observer pattern for Java design patterns

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.