Code for implementing the observer mode in ruby, javascript, and php, and ruby observer

Source: Internet
Author: User

Code for implementing the observer mode in ruby, javascript, and php, and ruby observer

When I was asked about the observer mode in js during the interview, I have long known about this. It can be said that it is a very useful design mode in Dynamic Language and I am ashamed that I have not studied it systematically. But it doesn't matter. If you don't know where to fill it up, do it right away and use all the languages you use.

Observer Mode

With regard to the observer mode, let's talk about the procedural World: The Observer Mode means that when the state of an object changes, all objects dependent on the state are automatically notified, the relationship between the observer and the observer is one-to-many. The book also provides an easy-to-understand example: Get the current system time and output it to the command line. If hard encoding is required, define a method to obtain the time and then process the display. In this way, the function of obtaining the time cannot be reused, because it contains a drag bottle for processing the display.

If the observer mode is used, you can define two classes, one for timing and obtaining the current time, and the other for displaying the time. The class that shows time is the observer. The advantage of doing so is to reduce mutual dependencies. The first class does not need to deal with anything after a change. Instead, it only needs to send a notification to its observers who will handle specific things. For example, if one day we want to display the time in another way or in multiple ways, we do not need to involve the first class.

PS: It's a good book to let everyone know about the world. At first, I wanted to read this book as a ruby tutorial. Later I found that it was not at all. I used a very easy-to-understand language to explain a lot of profound philosophical thoughts. Although this book is of little practical value to me, I am a beginner, but after reading it, I feel suddenly enlightened and it is a very good reading experience.

Ruby implementation

Using ruby to implement the observer mode is simple and clear, and the code is as follows:

Copy codeThe Code is as follows:
Require "observer"
# Observer
Class Subject
Include Observable
Def Policy
# Do something
Changed # update flag is true
Notify_observers (* args) # If the update flag is true, call the observer's method with The args parameter.
End
End
# Observer
Class Obs
# The callback function can only be called this way.
Def update
# Do something
End
End
# Instance
Sub = Subject. new
Sub. add_observer (Obs. new)
Sub. Policy

Yes, it's that simple...
It mainly relies on the Observer module. In addition to the above, this module also has the following interfaces:

1. delete_observer (obj) deletes a specified observer.
2. delete_observers: delete all observers
3. count_observers obtains the number of observers.
4. changed? Check the update flag

Php implementation

Php implementation is not troublesome:
Copy codeThe Code is as follows:
// Observer
Class Subject
{
Private $ _ observers;
Public function _ construct (){
$ This-> _ observers = array ();
}
Public function add_observer ($ obs ){
$ This-> _ observers [] = $ obs;
}
Public funtion delete_observer ($ bos ){
$ Index = array_search ($ bos, $ this-> _ observers );
Unset ($ this-> _ observers [$ index]);
}
Public function policy_observers (){
Foreach ($ this-> _ observers as $ v ){
$ V-> update ();
}
}
}
// Observer
Class Observer
{
Public function _ construct (){
Do something;
}
Public function update (){
Do something;
}
}
// Instance
$ Sub = new Subject ();
$ Obs = new Observer ();
$ Sub-> add_observer ($ obs );
$ Sub-> policy_observers ();

Js implementation

Javascript is easy to implement, that is, you have to write some tool functions for ease of use, such as deleting the elements specified by the array. The following uses only the simplest implementation method.
Copy codeThe Code is as follows:
// Observer
Function Subject (){
Var _ this = this;
This. observers = [];
This. addObserver = function (obj ){
_ This. observers. push (obj );
}
This. deleteObserver = function (obj ){
Var length = _ this. observers. length;
For (var I = 0; I <length; I ++ ){
If (_ this. observers [I] === obj ){
_ This. observers. splice (I, 1 );
}
}
}
This. policyobservers = function (){
Var length = _ this. observers. length;
Console. log (length)
For (var I = 0; I <length; I ++ ){
_ This. observers [I]. update ();
}
}
}
// Observer
Function Observer (){
This. update = function (){
Alert (1)
}
}
Var sub = new Subject ();
Var obs = new Observer ();
Sub. addObserver (obs );
Sub. policyobservers ();
Var sub = new Subject ();

Conclusion: ruby allows us to focus on program design rather than program syntax and features. Js is flexible and changeable. It is a complete programming language that can implement everything except for children. Php, it's just fine.

After all the worker programs run, they fully understand the design pattern.


How many languages do computer students need to know during interviews? Many students are learning PHP, Javascript, Ruby, Python, and Has.

C/C ++: This is used for most underlying tools and components. There are not as many job opportunities as java in China. Programmers have higher requirements. Applications include php ruby python extensions, hack nginx mysql and other open-source components. It may be possible to find a more closely bound profession with the OS, such as a non-java Embedded System.
Php: the true language of the Internet. The output site is definitely the first.
Ruby/Python: These two are actually OS scripting languages. programmers can help you reduce your daily work intensity and do something useful to you. A small number of websites are also useful for this development. Their personal output efficiency must be higher than that of the Java framework. However, the treatment is actually based on your experience, so there are not many people to learn.
Fresh graduates can really work like this, so they don't have to find a decent job. If you really want to use C/C ++/Java and Python, you will not be so anxious.

What is the use of javascript observer mode and custom events?

Javascript itself is a language that supports asynchronous programming. This is its power. The observer mode uses function callback to implement asynchronous programming. When an event is triggered, all subscribers receive messages and call corresponding processing functions without real-time monitoring, this obviously greatly improves the cpu utilization in some situations. Custom events are the practical use of asynchronous programming, so that you can execute the operation code (trigger the event) when you want to execute it, rather than the traditional top-down execution, added code flexibility. In addition, code redundancy is reduced. For the same operation, you only need to trigger the same event and do not need to write it again.
 

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.