Developing a micro-public number example using the Observer pattern in the Java design pattern _java

Source: Internet
Author: User

Remember the police and bandits on the film, the Bandits are how to cooperate with the implementation of crime? When a gang is in the act of stealing, there are always one or two people standing guard at the door-if anything happens, they will immediately notify the accomplice of the emergency evacuation. Maybe the people in the yard don't necessarily know every one of them, and there may be new boys who don't know this lookout. But it's nothing, it doesn't affect the communication between them, because they have already agreed to a good signal.
Hehe, the relationship between the spotter and the thief mentioned above is a vivid example of the observer model in reality.

The Observer (Observer) mode is also named publish-subscribe (publish/subscribe) mode. GOF gives the observer pattern the following definition: 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.
First of all, here is an important principle of object-oriented design-the principle of single responsibility. Therefore, each object of the system should focus on the discrete abstraction in the problem domain. So ideally, an object would only do one thing. This also brings a lot of benefits in development: it provides reusability and maintainability, and is a good foundation for refactoring.
So almost all design patterns are based on this basic design principle. The origin of the observer pattern I think should be in the GUI and business data processing, because now most of the example of the observer model is this subject. But the application of the observer model is by no means limited to this aspect.


Well, for the definition of understanding always need an example to resolve, today's micro-letter service is quite fire ah, the following is based on the micro-letter service number for the background, to introduce the observer model.
Look at a picture:

Each of these users has 3 lines in the above image, in order to make the picture clearly omitted.
As shown in the figure above, the service number is our subject, and the user is the observer. Now we have a clear function:
1, service number is the theme, the business is to push messages
2, the observer only need to subscribe to the subject, as long as there is a new message will be sent
3. Unsubscribe when you don't want this topic message
4, as long as the service number is still, there will always be someone to subscribe
OK, now let's take a look at the class diagram of the Observer pattern:

Next is the code time, we simulate a micro-letter 3D lottery service number, and some subscribers.
Start by writing our theme interface, and the Observer interface:

Package com.zhy.pattern.observer; 
 
/** 
 * Theme interface, all the themes must implement this interface * * @author zhy * * * * * * * public 
interface Subject 
{ 
  /** 
   * Register an observation 
   * 
   * @param observer 
   /public 
  VOID REGISTEROBSERVER (Observer observer); 
 
  /** * 
   Remove an observer 
   * 
   * @param observer/public 
  VOID REMOVEOBSERVER (Observer observer); 
 
  /** 
   * Notifies all the observed * 
  /public void notifyobservers (); 
 
} 

Package com.zhy.pattern.observer; 
 
/** 
 * @author Zhy All observers need to implement this interface * 
 * Public 
interface Observer 
{public 
  void update (String msg) ; 
 
} 

Next, the implementation class for the 3D service number:

Package com.zhy.pattern.observer; 
 
Import java.util.ArrayList; 
Import java.util.List; 
 
public class Objectfor3d implements Subject 
{ 
  private list<observer> observers = new arraylist< Observer> (); 
  /** 
   * 3D Lottery number * 
  /private String msg; 
 
  @Override public 
  void Registerobserver (Observer Observer) 
  { 
    observers.add (Observer); 
  } 
 
  @Override public 
  void Removeobserver (Observer Observer) 
  { 
    int index = Observers.indexof (Observer); 
    if (index >= 0) 
    { 
      observers.remove (index); 
    } 
  } 
 
  @Override public 
  void Notifyobservers () 
  {for 
    (Observer observer:observers) 
    { 
      Observer.update (msg); 
    } 
 
  /** 
   * Theme Update Message 
   * * 
   @param msg * 
   /public 
  void Setmsg (String msg) 
  { 
    this.msg = msg; 
     
    Notifyobservers (); 
  } 
 
 

Simulate two users:

Package com.zhy.pattern.observer; 
 
public class Observer1 implements Observer 
{ 
 
  private Subject Subject; 
 
  Public Observer1 (Subject Subject) 
  { 
    this.subject = Subject; 
    Subject.registerobserver (this); 
  } 
 
  @Override public 
  void Update (String msg) 
  { 
    System.out.println (observer1) Gets the 3D number--> "+ msg +", I want to write it down. "); 
  } 
 
} 


Package com.zhy.pattern.observer; 
 
public class Observer2 implements Observer 
{ 
  private Subject Subject;  
   
  Public Observer2 (Subject Subject) 
  { 
    this.subject = Subject; 
    Subject.registerobserver (this); 
  } 
   
  @Override public 
  void Update (String msg) 
  { 
    System.out.println ("Observer2 get 3D number-->" + msg + "I'm going to tell the roommates 。 "); 
  } 
   
   
 
} 

As you can see, all users who subscribe to it are maintained in the service number, and all consumers are notified when the service number has a new message. The entire architecture is loosely coupled, the implementation of the theme is not dependent on the user, and when new users are added, the subject code does not need to change, and how the user handles the resulting data is irrelevant to the subject;
Finally look at the test code:

Package com.zhy.pattern.observer.test; 
 
Import Com.zhy.pattern.observer.ObjectFor3D; 
Import Com.zhy.pattern.observer.Observer; 
Import Com.zhy.pattern.observer.Observer1; 
Import Com.zhy.pattern.observer.Observer2; 
Import Com.zhy.pattern.observer.Subject; 
 
public class Test 
{public 
  static void Main (string[] args) 
  { 
    //simulate a 3D service number 
    Objectfor3d Subjectfor3d = new Objectfor3d (); 
    Customer 1 
    Observer observer1 = new Observer1 (subjectfor3d); 
    Observer observer2 = new Observer2 (subjectfor3d); 
 
    Subjectfor3d.setmsg ("20140420 of the 3D number is: 127"); 
    Subjectfor3d.setmsg ("20140421 3D number is: 333"); 
     
  } 
 

Output results:

Observer1 get 3D number-->20140420 3D number is: 127, I want to write down. 
Observer2 Get the 3D number-->20140420 3D number is: 127 I want to tell the roommate. 
Observer1 get 3D number-->20140421 3D number is: 333, I want to write down. 
Observer2 Get the 3D number-->20140421 3D number is: 333 I want to tell the roommate. 

There are many places in the JDK or andorid that implement the observer pattern, such as xxxview.addxxxlistenter, of course. Xxxview.setonxxxlistener is not necessarily the observer pattern, because the Observer pattern is a one-to-many relationship, and for Setxxxlistener to be a 1 to 1 relationship, it should be called a callback.

Congratulations you have learned the observer pattern, the above observer pattern allows us to write from scratch, of course, Java has helped us achieve the observer pattern, with the help of Java.util.Observable and Java.util.Observer.
Here we use the Java built-in class to implement the Observer pattern:

The first is a 3D lottery service number theme:

Package Com.zhy.pattern.observer.java; 
 
Import java.util.Observable; 
 
public class Subjectfor3d extends observable 
{ 
  private String msg;  
   
   
  Public String getmsg () 
  {return 
    msg; 
  } 
 
 
  /** 
   * Theme Update Message 
   * * 
   @param msg * 
   /public 
  void Setmsg (String msg) 
  { 
    this.msg = msg; 
    Setchanged (); 
    Notifyobservers (); 
  } 
 

The following is a SHUANGSE Qiu Service number topic:

Package Com.zhy.pattern.observer.java; 
 
Import java.util.Observable; 
 
public class SUBJECTFORSSQ extends observable 
{ 
  private String msg;  
   
   
  Public String getmsg () 
  {return 
    msg; 
  } 
 
 
  /** 
   * Theme Update Message 
   * * 
   @param msg * 
   /public 
  void Setmsg (String msg) 
  { 
    this.msg = msg; 
    Setchanged (); 
    Notifyobservers (); 
  } 
 

And finally, our users:

Package Com.zhy.pattern.observer.java; 
 
Import java.util.Observable; 
Import Java.util.Observer; 
 
public class Observer1 implements Observer 
{public 
 
  void Registersubject (observable observable) 
  { 
    Observable.addobserver (this); 
  } 
 
  @Override public 
  void update (Observable o, Object Arg) 
  { 
    if (o instanceof subjectfor3d) 
    { 
      Subjectfor3d Subjectfor3d = (subjectfor3d) o; 
      System.out.println ("Subjectfor3d ' MSG-->" + subjectfor3d.getmsg ()); 
    } 
 
    if (o instanceof subjectforssq) 
    { 
      subjectforssq subjectforssq = (subjectforssq) o; 
      System.out.println ("Subjectforssq ' MSG-->" + subjectforssq.getmsg ());} 
    } 
 

Look at a test code:

Package Com.zhy.pattern.observer.java; 
 
public class Test 
{public 
  static void Main (string[] args) 
  { 
    Subjectfor3d subjectfor3d = new Subjectfor3d (); 
    SUBJECTFORSSQ subjectforssq = new subjectforssq (); 
     
    Observer1 observer1 = new Observer1 (); 
    Observer1.registersubject (Subjectfor3d); 
    Observer1.registersubject (SUBJECTFORSSQ); 
     
     
    Subjectfor3d.setmsg ("Hello 3d ' nums:110"); 
    Subjectforssq.setmsg ("Ssq ' nums:12,13,31,5,4,3"); 
     
  } 
 

Test results:

Subjectfor3d ' s MSG-->hello 3d ' nums:110  
subjectforssq ' s MSG-->SSQ ' nums:12,13,31,5,4,3 15 

The

can see that the Java-built class implements the observer pattern, the code is very concise, and Addobserver,removeobserver,notifyobservers has been implemented for us, All can see that observable (subject) is a class, not an interface, basically the book on the Java design has a negative attitude, that the Java built-in Observer mode, the violation of the principle of interface-oriented programming, but if you think about it, It is true that you take a theme here to write the Observer pattern (our own implementation), the interface is good, but if you continue to add a lot of topics now, the Ddobserver,removeobserver,notifyobservers code for each topic is basically the same, Interfaces are not code reusable, and there is no way to reuse these three methods using a combination of patterns, so I think it is reasonable to implement these three methods in the class.

Related Article

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.