One of the great benefits of object-oriented programming is polymorphism; i.e., the ability to send a message to an object without knowing the true type of the object Perhaps no pattern illustrates this better than the Strategy pattern..
To illustrate the Strategy pattern let's assume that we are working on a debug logger. Debug loggers are often very useful devices. Programmers can send messages to these loggers at strategic places within the code. If the system misbehaves in some way, the debug log can Provide Clues About What The System Was Doing Internal At The Time of the Failure.
In order to be effective, loggers need to be simple for programmers to use Programmers are not going to frequently use something that is inconvenient You should be able to emit a log message with something no more complicated than..:
Logger.log ("My Message");
On The Other Hand, What We want to see in the log is quite a bit More complex. At Very Least WE a Going to Want To See The Time and Date of the Message. We'll Also Probably Want To See The Thread ID. Indeed, there may be a whole laundry list of system states that we want to log along with the message. So the logger needs to gather all of this peripheral information together, format it into a log message, and then add it to the growing list of logged messages.
Where should the logged messages be stored? Sometimes we might like them stored in a text file. Sometimes we might want to see them added to a database table. Sometimes we might like them accumulated in RAM. The choices seem endless. However, the final Destination of the logged message. Nothing to do with the format of the message..
We have two algorithms:.. One formats the logged message, and the other records the logged message These two algorithms are both in the flow of logging a message, but both can vary independently of each other The formatter does not care where the message is . recorded, and the recorder does not care about the format of the message Whenever we have two connected but independent algorithms, we can use the Strategy pattern to connect them Consider the following structure:. Here the user calls the log method of the Logger class .................. ..
The structure of the logger and recorder is exemplified by The Following Unit Test, Which Uses The adapter pattern:
Public class loggertest extends testcase {
Private string recording;
Protected string message;
Public void testlogger () throws exception {
Logger Logger = New Logger (New Recorder () {
Public void record (string message) {
RecordedMessage = Message;
}
});
Message = "mymessage";
Logger.log (Message);
Checkformat ();
}
Private vid checkformat () {
String datepattern = "// d {2} /// D {2} /// D {4} //d}} //}: {3 } "
String messagePattern = datepattern " message;
IF (! Pattern.matches (messagepattern, recordingMessage) {
Fail (RecordedMessage "Does Not Match Pattern");
}
}
}
As you can see, the Logger is constructed with an instance of an object that implements the Recorder interface. Logger does not care what that implementation does. It simply builds the string to be logged and then calls the record method. This is very powerful decoupling . It is the recorder.
Public class logger {
Private Recorder Recorder;
Public logger (Recorder Recorder) {
This.Recorder = Recorder;
}
Public void log (string message) {
DateFormat Format = New SimpleDateFormat ("MM / DD / YYYY KK: MM: SS.SSS");
Date now = new date ();
String prefix = Format.Format (now);
Recorder.Record (Prefix " Message);
}
}
And Recorder is an Even SIMPLER INTERFACE.
Public interface recorder {
Void Record (String Message);
}
The canonical form of the Strategy pattern is shown below. One algorithm (the context) is shielded from the other (the strategy) by an interface. The context is unaware of how the strategy is implemented, or of how many different implementations there are. The Context Typically Holds a Pointer Or Reference To The Strategy Object with Which It Was Constructed.
In Our Logger Example, The Logger Is The Context, The Recorder Is The Strategy Interface, and the anonymous inner class.
If you have been an object-oriented programmer for any length of time, you have seen this pattern many times. Indeed, it is so common that some folks shake their heads and wonder why it even has a name. It's rather like giving the name . "DO NEXT STATEMENT" to the fact that execution proceeds statement by statement However, there is a good reason to give this pattern a name It turns out that there is another pattern that solves the same problem in a slightly different way;. and the two names help us differentiate between them.This second pattern is called Template Method, and we can see it by adding the next obvious layer of polymorphism to the Logger example. We already have one layer that allows us to change the way log messages are recorded .. We could add another layer to allow us to change how log messages are formatted Let's suppose, for instance, that we want to support two different formats One prepends the time and date to the message as above;. the other prepends only the time .
Clearly, this Is Just Another Problem in Polymorphism, And We Could Use The Strategy Pattern Once Again. IF WE DID, THE Design Might Look Like this:
Here we see two uses of the Strategy pattern. One provides polymorphic recording and the other provides polymorphic formatting. This is a common enough solution, but it is not the only solution. Indeed, we might have opted for a solution that looked more like this :
Notice the format method of Logger. It is protected (that's what the # means) and it is abstract (that's what the italics mean). The log method of Logger calls its own abstract format method, which deploys to one of the derived classes. The formatted string is then passed to the record method of the Recorder.Consider the unit test below. It shows tests for both the TimeLogger and the TimeDateLogger. Notice that each test method creates the appropriate Logger derivative and passes a Recorder instance into it.
Import junit.framework.testcase;
Import java.util.Regex.pattern;
Public class loggertest extends testcase {
Private string recording;
Protected string message;
Private static final string timedateFormat =
"// D {2} /// D {2} /// D {4} //d}: {2}: (});
Private static final string timeformat = "//d}: {2 }.//d{3}"
Private recorder recorder = new recorder () {
Public void record (string message) {
RecordedMessage = Message;
}
}
Public void testTIMEDATELOGER () throws exception {
Logger logger = new TIMEDATELOGGER (RECORDER);
Message = "mymessage";
Logger.log (Message);
Checkformat (TIMEDATEFORMAT);
}
Public void testtimelogger () throws exception {
Logger Logger = New TimeLogger (RECORDER);
Message = "mymessage";
Logger.log (Message);
Checkformat (TimeFormat);
}
Private void Checkformat (String prefix) {
String messagePattern = prefix " message;
IF (! Pattern.matches (messagepattern, recordingMessage) {
Fail (RecordedMessage "Does Not Match Pattern");
}
}
}
The Logger Has Changed As Follows. NOTICE The Protected Abstract Format Method.
Public Abstract Class Logger {
Private Recorder Recorder;
Public logger (Recorder Recorder) {
This.Recorder = Recorder;
}
Public void log (string message) {
Recorder.record (Format (Message);
}
Protected Abstract string format;
}
Timelogger and Timedatelogger Simply Implement The Format Method Appropriate To Their Type, AS Shown Below:
Import java.text. *;
Import java.util.date;
Public class timelogger extends logger {
Public TimeLogger (Recorder Recorder) {
Super (Recorder);
}
Protected string format (string message) {
DateFormat Format = New SimpleDateFormat ("KK: MM: SS.SSS");
Date now = new date ();
String prefix = Format.Format (now);
Return prefix " message;
}
}
Import java.text. *;
Import java.util.date;
Public class timedatelogger extends logger {
Public Timedatelogger (Recorder Recorder) {
Super (Recorder);
}
Protected string format (string message) {
DateFormat Format = New SimpleDateFormat ("MM / DD / YYYY KK: MM: SS.SSS");
Date now = new date ();
String prefix = Format.Format (now);
Return prefix " message;
}
}
The Canonical Form of Template Method Looks Like this:
The Context class has at least two functions. One (here called function) is generally public, and represents some high-level algorithm. The other function (here called subFunction) represents some lower-level algorithm called by the higher-level algorithm. The DeriVative of Context IMPLEMENT SUBFUNCETONTYS.
It should be clear how Strategy and Template Method solve the same problem. The problem is simply to separate a high-level algorithm from a lower-level algorithm in such a way that the two can vary independently. In the case of Strategy, this is solved by creating an interface for the lower-level algorithm. In the Template Method case, it is solved by creating an abstract method.Strategy is preferable to Template Method when the lower-level algorithm needs to change at run time. This can be accomplished with Strategy simply by swapping in an instance of a different derivative Template Method is not so fortunate;. once created, its lower-level algorithm is locked in On the other hand, Strategy has a slight time and space penalty compared to Template Method,. And is more complex to set up. so strategy shop be used when flexibility is importraftant, and template method be used when Time and space Efficiency and Simplicity Are More Important.
COULD WE HAVE Used Template Method To Solve The WHOLGER PROBLEM? YES, But The Result IS Not Pleasant. Consider The Following Diagram.
Notice that there is one derivative for each possible combination. This is the dreaded m x n problem. Given two polymorphic degrees of freedom (e.g., recording and format) the number of derivatives is the product of those degrees.
This Problem is Common Enough That The Combined Use of Strategy And Template Method To Solve IT (As We Did In The Previous Example) Is A Pattern In And of Itself, Called Bridge.