comp.object新闻组上发布的一个关于OO思考和重构的极好例子,非常简单,但请仔细揣摩,可以把自己的结果拿出来大家品评
First, write a program that can forward sort lines of text from standard
input and write them to standard output. Don't worry about any other
requirements and don't write the program to do anything more than the
sort in question. Oh, and since this is a learning exorcise, don't use
the STL... :-)
Now add in a command line option to "sort in reverse". Notice that
somewhere in your program, you have to do something different based on
whether the sort is forward or reverse. Now I want you to be creative
and arrange the code so that the if check on the reverse flag is only
done once during runtime. In other words, if you put the check inside a
loop somewhere, it will be called every pass, instead put the check
outside all the loops and use an abstract class that has a method that
tells the algorithm which which item goes first, then the if check
creates a concrete object from a sub-class of that abstract class.
Now add a command line flag to sort numerically. If this flag is set,
the program should parse input as integers and sort them. It should not
sort strings with this flag set. :-) Again, the flag should only be
examined once during runtime. Of course you must make sure that the
"sort in reverse" flag still works.
When you are done with this step, you should have a program that (1)
checks the flags and creates some objects based on how they are set, (2)
reads the input and uses one or more of the objects created above to
parse it, (3) sorts the items, again using one or more of the objects
created in step 1 to decide the sort order, then (4) outputs the items,
again using one or more of the objects created in step 1.
Now ask yourself, how hard would it be to use the sorting algorithm for
sorting doubles? What if you wanted it to sort shapes by size? Would you
have to make any changes to the actual input, sort, and output sections
of the program, or only to the "check the flags and create some objects"
part?
Extra Credit: add a command line option that allows the user to change
the sort algorithm being used...
If desired, e-mail the program to me (replace "postmaster" with
"daniel_t"), or post it on this newsgroup and let us critique it...
As you come to understand what "they" are talking about in the example,
you will find that you routinely write program units that can work in a
variety of contexts, just like the input, sort, and output units in the
above program work for many different situations, even ones you haven't
thought of yet.