Design Pattern-Observer pattern (Observer)

Source: Internet
Author: User

Design Pattern-Observer pattern (Observer)
What is the observer mode?Defines a one-to-many relationship, allowing multiple observer objects (company employees) to listen to a topic object (Secretary) at the same time. When the status of the topic object changes, all observers are notified, enable them to update themselves. What problems can be solved? Splitting a system into a class that cooperates with each other has a bad side effect, that is, maintaining consistency between related objects. We do not want to make all kinds of Close coupling to maintain consistency, which will cause inconvenience to maintenance, expansion and reuse. The observer solves such Coupling Relationships.
RolesAbstract topic: It stores reference of all observer objects in one aggregation. Each topic can have any number of observers. Abstract topic provides an interface to add and delete observer objects. ConcreteSubject: stores the status in a specific observer object, and sends a notification to all registered observers when the status of the subject changes. Abstract Observer: defines an interface for all specific observers and updates themselves when receiving topic notifications. ConcreteObserver: implements the update interface required by the abstract observer role to coordinate its status with the topic status.
Instance description:

// Abstract observer role public interface Watcher {public void update (String str );}
// Define an abstract topic role, that is, an abstract observer // abstract topic role. watched: public interface Watched {public void addWatcher (Watcher watcher ); public void removeWatcher (Watcher watcher); public void policywatchers (String str);} public class ConcreteWatcher implements Watcher {@ Override public void update (String str) {System. out. println (str );}}
// Topic role import java. util. ArrayList; import java. util. List; public class ConcreteWatched implements Watched {// stores the observer private List
 
  
List = new ArrayList
  
   
(); @ Override public void addWatcher (Watcher watcher) {list. add (watcher) ;}@ Override public void removeWatcher (Watcher watcher) {list. remove (watcher) ;}@ Override public void policywatchers (String str) {// automatic call is actually called by the topic for (Watcher watcher: list) {watcher. update (str );}}}
   
  
 
// Testpublic class Test {public static void main (String [] args) {Watched girl = new ConcreteWatched (); Watcher watcher1 = new ConcreteWatcher (); watcher watcher2 = new ConcreteWatcher (); Watcher watcher3 = new ConcreteWatcher (); girl. addWatcher (watcher1); girl. addWatcher (watcher2); girl. addWatcher (watcher3); girl. notifyWatchers (happy );}}
 
/*** Observer Mode Application Scenario instance ** Disclaimer: This article uses the ticket network as an example. The example does not involve any business code of the ticket network, and is all original. If there are similarities, it is a coincidence. ** Scenario Description: * ticket purchasing is the core business (this mode is not limited to this business), but other logic is generated around ticket purchasing, such: * 1. Record text logs after ticket purchase * 2. Record database logs after ticket purchase * 3. send SMS messages after ticket purchase * 4. receive discount coupons, redeem coupons, points * 5 for tickets, and other activities and other ** traditional solutions: * Add related code to the ticket logic and other categories to complete various logics. ** Problems: * 1. Once a business logic changes, such as adding other business logic to the ticket purchasing business, you need to modify the core ticket purchasing documents or even the ticket purchasing process. * 2. After days and months, the document is lengthy, resulting in difficulties in subsequent maintenance. ** The main cause of the problem is the close coupling of the program. The observation mode is used to optimize the current business logic into loose coupling for easy maintenance and modification, * It also conforms to the idea of interface-oriented programming. ** Typical Implementation of observer mode: * 1. Define two interfaces: Observer (notification) interface, observer (topic) interface * 2. Define two classes, the observer object implements the observer interface and the topic class implements the viewer interface * 3. The topic class registers the observer to be notified * 4. The observer object is notified when a business logic of the topic class occurs, each Observer executes its own business logic. ** Example: for example, the following code **/# ======================== defines the observer and the observer interface ======== ===/ ***** observer interface (Notification Interface) **/InterfaceITicketObserver // observer interface {FunctionOnBuyTicketOver ($ sender, $ args); // method called after notification}/***** topic interface **/InterfaceITicketObservable // interface of the observed object {FunctionAddObserver ($ observer ); // provides the method for registering an observer. ===================/***** topic categories (purchase tickets) **/ClassHipiaoBuyImplementsITicketObservable {// implement the topic interface (observer)Private$ _ Observers =Array(); // Notification array (observer)Public functionBuyTicket ($ ticket) // core ticket purchasing class, ticket purchasing process {//TODOPurchase logic // circular notification, calling its onBuyTicketOver to implement different business logicForeach($ This-> _ observersAs$ Obs) $ obs-> onBuyTicketOver ($ this, $ ticket); // $ this can be used to obtain the topic class handle and use it in notification} // Add a notificationPublic functionAddObserver ($ observer) // Add N notifications {$ this-> _ observers [] = $ observer ;}} #=========================================define multiple notifications ============/// SMS log notificationClassHipiaoMSMImplementsITicketObserver {Public functionOnBuyTicketOver ($ sender, $ ticket ){Echo(Date ('Y-m-d H: I: s'). SMS log record: ticket purchase successful: $ ticket) ;}// text log notificationClassHipiaoTxtImplementsITicketObserver {Public functionOnBuyTicketOver ($ sender, $ ticket ){Echo(Date ('Y-m-d H: I: s'). text log record: ticket purchase successful: $ ticket) ;}// coupon notificationClassHipiaoDiKouImplementsITicketObserver {Public functionOnBuyTicketOver ($ sender, $ ticket ){Echo(Date ('Y-m-d H: I: s'). discount coupon: ticket purchase successful: $ ticket: One 10 yuan discount coupon .); }}#================================================= =================$ Buy =NewHipiaoBuy (); $ buy-> addObserver (NewHipiaoMSM (); // Add various notifications according to different business logic $ buy-> addObserver (NewHipiaoTxt (); $ buy-> addObserver (NewHipiaoDiKou (); // buy tickets $ buy-> buyTicket (first in a row );
 

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.