Object-Oriented Programming With ANSI-C (pdf)
Object-Oriented Programming With ANSI-C (pdf)
Object-Oriented Programming With ANSI-C (pdf)
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
122 __________________________________________________________________________<br />
10 Delegates — Callback Functions<br />
10.7 Another application — sort<br />
Let us implement a small text sorting program to check if Filter really is reusable, to<br />
see how command line options are handled, and to appreciate that a delegate can<br />
belong to an arbitrary class.<br />
A sort filter must collect all text lines, sort the complete set, and finally write<br />
them out. Section 7.7 introduced a List based on a dynamic ring buffer which we<br />
can use to collect the lines as long as we add a sorting method. In section 2.5 we<br />
implemented a simple String class; if we integrate it with our class hierarchy we<br />
can use it to store each line in the List.<br />
Let us start with the main program which merely creates the filter with its<br />
delegate:<br />
int main (int argc, char * argv [])<br />
{ void * filter = new(Filter(), new(Sort(), 0));<br />
return mainLoop(filter, argv);<br />
}<br />
Because we can attach the callback methods to any class, we can create the<br />
delegate directly in a subclass of List:<br />
% SortClass: ListClass Sort: List {<br />
char rflag;<br />
%—<br />
void flags (_self, <strong>Object</strong> @ filter, char flag);<br />
int line (_self, const <strong>Object</strong> @ filter, const char * fnm, \<br />
char * buf);<br />
int quit (_self, const <strong>Object</strong> @ filter);<br />
%}<br />
To demonstrate option handling we recognize −r as a request to sort in reverse<br />
order. All other flags are rejected by the flags() method which has flag as a tag for<br />
respondsTo():<br />
% flag: Sort flags {<br />
%casts<br />
assert((flagM) flags == flags);<br />
if (flag == ’r’)<br />
self —> rflag = 1;<br />
else<br />
fprintf(stderr, "usage: %s [—r] [file...]\n",<br />
progname(filter)),<br />
exit(1);<br />
}<br />
Given String and List, collecting lines is trivial:<br />
% Sort line {<br />
%casts<br />
assert((lineM) line == line);<br />
addLast(self, new(String(), buf));<br />
return 0;<br />
}