Article Source: csdn Author: wangfengsdu
The notion of a callback function (callback function) is often heard, called a callback function, meaning that the function is registered somewhere, and it will be invoked at a later time when needed. For example, when using the SDK for Windows programming, we need to register a WNDCLASS class, this class has such a parameter lpfnwndproc, for message processing, we have to process the message of the function of the pointer to it to assign value. When did the message handler function be invoked? We didn't see it explicitly in the program. is called by the OS. This is the SDK test method, of course, with the procedural language C, can be passed through the function of the pointer implementation.
How to achieve in C + +? C + +, of course, can be used with function pointers. At the same time, C + + provides an object-oriented mechanism, can there be different implementation mechanism? Of course! The functor (Function object) in the STL can be used on the callback. For example, we can do this in descending order of a vector that holds int data.
Sort (Vec.begin (), Vec.end (),greater<int> ());
Greater<int> ()
Is the anonymous object we passed, which overloaded the function call operator "()". We don't explicitly call the function provided in this object, and the sort function calls back to the function inside the object.
Java in order to implement similar functor function, what should do? Command mode can help. Command mode looks simple, as long as you encapsulate the command in one interface. Command mode is an object-oriented alternative to the callback mechanism.
For example, an interface that has already been defined in java.io
Public interface FilenameFilter {
Boolean Accept (File dir, String name);
}
The filenamefilter is the command, and the class that implements the command is Concretecommand. The operation "Accept" declared by this interface is to see if the file name in directory dir satisfies a requirement, returns true if satisfied, or returns false. What is the requirement? You have to implement this interface. For example, I want to see the name of this file contains a string that does not contain the specified, so you can define the following class:
Class Dirfilter implements FilenameFilter {
Private String AFN;
Public Dirfilter (String AFN) {
This.afn = AFN;
}
Public Boolean Accept (File dir, String name) {
String f = new File (name). GetName ();
Return F.indexof (AFN)!=-1;
}
}
How do you use it? There is a method in the file class
Public string[] List (filenamefilter filter)
So we can do this:
File File = new file (".");
string[] List = file.list (new Dirfilter ("WF"));
The resulting list is a string array of all the file names that contain the string "WF" in the directory. What, does it look like the functor in C + +?