The Observer pattern is also known as the publish-subscribe mode, which is designed to solve the coupling between the subject object and the Observer's function. Publishers and Subscribers are non-intrusive, unconnected, and through observers, as intermediaries, connect the two.
Example: Taking the student and teacher as an example
1. First create the Observer object
Place the observer in the closure and execute immediately when the page loads
var Observer = (function () {
Prevents Message Queuing from being tampered with, saving the message container as a static private variable
var _message = {};
return {
Registration Information Interface
Regist:function () {},
Publishing an Information interface
Fire:function () {},
Removing an information interface
Remove:function () {}
}
}) ()
2. Create student classes and related methods
Student class
var Student = function (Result) {
var = this;
That.result = result;
Students answer questions and actions
That.say = function () {
Console.log (That.result);
}
}
The way students answer questions
Student.prototype.answer = function (question) {
Console.log (This.result + ' + question + ' answer question ')
Registration parameter issues
Observer.regist (question, This.say)
}
The student sleeps, at this time cannot answer the question the method
Student.prototype.sleep = function (question) {
Console.log (This.result + ' + question + ' has been unregistered ')
To cancel the monitoring of teachers ' problems
Observer.remove (question, This.say)
}
3. Creating teacher classes and related methodologies
Teacher Class
var Teacher = function () {};
The method of teacher asking questions
Teacher.prototype.ask = function (question) {
Console.log (' The problem is: ' + question ');
Post a question message
Observer.fire (question)
}
4. Create an entity class
/Simulate 3 students who are attending lectures
var student1 = new Student (' Student 1 answer question '),
Student2 = new Student (' Students 2 answer questions '),
Student3 = new Student (' Students 3 answer questions ');
3 students Listening (subscribed) Two questions raised by the teacher
Student1.answer (' What is design mode 1 ');
Student1.answer (' Brief description of Observer Pattern 1 ');
Student2.answer (' What is design mode 2 ');
Student2.answer (' Brief description of Designer Mode 2 ');
Student3.answer (' What is design mode 3 ');
Student3.answer (' Brief description of Observer Pattern 3 ');
The third student was asleep and canceled the second question of the subscription
Student3.sleep (' Brief description of Observer Pattern 3 ');
Create a teacher class
var teacher = new Teacher ();
The teacher asked two questions.
Teacher.ask (' What is design mode ');
Teacher.ask (' Brief description of the Observer model ');
The observer pattern of JS design mode