Difference between Strategy pattern and Command pattern

JavaDesign PatternsStrategy PatternCommand Pattern

Java Problem Overview


What is the difference between the Strategy pattern and the Command pattern? I am also looking for some examples in Java.

Java Solutions


Solution 1 - Java

Typically the Command pattern is used to make an object out of what needs to be done -- to take an operation and its arguments and wrap them up in an object to be logged, held for undo, sent to a remote site, etc. There will tend to be a large number of distinct Command objects that pass through a given point in a system over time, and the Command objects will hold varying parameters describing the operation requested.

The Strategy pattern, on the other hand, is used to specify how something should be done, and plugs into a larger object or method to provide a specific algorithm. A Strategy for sorting might be a merge sort, might be an insertion sort, or perhaps something more complex like only using merge sort if the list is larger than some minimum size. Strategy objects are rarely subjected to the sort of mass shuffling about that Command objects are, instead often being used for configuration or tuning purposes.

Both patterns involve factoring the code and possibly parameters for individual operations out of the original class that contained them into another object to provide for independent variability. The differences are in the use cases encountered in practice and the intent behind each pattern.

Solution 2 - Java

Words are already given. Here is the difference in concrete code.

public class ConcreteStrategy implements BaseStrategy {

    @Override
    public void execute(Object argument) {
        // Work with passed-in argument.
    }

}

public class ConcreteCommand implements BaseCommand {

    private Object argument;

    public ConcreteCommand(Object argument) {
        this.argument = argument;
    }

    @Override
    public void execute() {
        // Work with own state.
    }

}

Solution 3 - Java

Strategy - Quicksort or Mergesort [algo change]

Command - Open or Close [action change]

Solution 4 - Java

The main difference is , the command does some action over the object. It may change the state of an object.

While Strategy decides how to process the object. It encapsulates some business logic.

Solution 5 - 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

  1. It's a behavioural pattern
  2. It's based on delegation
  3. It changes guts of the object by modifying method behaviour
  4. It's used to switch between family of algorithms
  5. It changes the behaviour of the object at run time

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 :

https://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern/35180265#35180265

https://stackoverflow.com/questions/2015549/using-command-design-pattern/34789979#34789979

Solution 6 - Java

I think a big difference here is that Strategy pattern is used when you need to shuffle between different objects that implement the same interface, but Command Pattern is used to shuffle between some objects that implement different interfaces ( as it encapsulates them into other objects called "Command Objects" ) and pass these command objects just like Strategy pattern does.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrishnaView Question on Stackoverflow
Solution 1 - JavaJeffrey HantinView Answer on Stackoverflow
Solution 2 - JavaBalusCView Answer on Stackoverflow
Solution 3 - JavaFakrudeenView Answer on Stackoverflow
Solution 4 - JavaAsif MalekView Answer on Stackoverflow
Solution 5 - JavaRavindra babuView Answer on Stackoverflow
Solution 6 - JavaAhmed ShalabyView Answer on Stackoverflow