What is the difference between the Strategy pattern and the Command pattern? I am also looking for some examples in Java.
Strategy pattern is useful when you have multiple implementations (algorithms) for a given feature and you want to change the algorithm at runtime depending on parameter type.
One good example from HttpServlet code:
service()
method will direct user's request to doGet() or doPost() or some other method depending on method type.
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
Salient features of Strategy pattern
Command pattern is used to enable loose coupling between Invoker and Receiver. Command, ConcreteCommand, Receiver, Invoker and Client are major components of this pattern.
Different Receivers will execute same Command through Invoker & Concrete Command but the implementation of Command will vary in each Receiver.
e.g. You have to implement "On" and "Off" functionality for TV & DVDPlayer. But TV and DVDPlayer will have different implementation for these commands.
Have a look at below posts with code examples :
Real World Example of the Strategy Pattern
Using Command Design pattern