A software example
Python uses the Template pattern in the cmd
module, which is used to build line-oriented command interpreters. Specifically, cmd.Cmd.cmdloop()
implements an algorithm that reads input commands continuously and dispatches them to action methods. What is done before the loop, after the loop, and the command parsing part are always the same. This is also called the invariant part of an algorithm. What changes are the actual action methods (the variant part) [j.mp/templatemart, page 27].
The Python module asyncore
, which is used to implement asynchronous socket service client/servers, also uses Template. Methods such as asyncore.dispather.handle_connect_event()
and asyncore.dispather.handle_write_event()
contain only generic code. To execute the socket-specific code, they execute the handle_connect()
method. Note that what is executed is handle_connect()
of a specific socket, not asyncore.dispatcher.handle_connect()
, which actually contains only a warning. We can see that...