Difference between Strategy pattern and Command pattern - java

What is the difference between the Strategy pattern and the Command pattern? I am also looking for some examples in 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.

Words are already given in the other answer. 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.
}
}

Strategy - Quicksort or Mergesort [algo change]
Command - Open or Close [action change]

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.

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
It's a behavioural pattern
It's based on delegation
It changes guts of the object by modifying method behaviour
It's used to switch between family of algorithms
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 :
Real World Example of the Strategy Pattern
Using Command Design pattern

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.

Related

Naming several chained functions that only do a small part of the job

I sometimes have this issue where a task is done by a set of functions, each of them actually just preparing the context and getting a bit closer to the original task, but only the last one is really doing the job, and naming each of them is a nightmare.
Here is an example that exhibits the naming issue:
/* This is the API, it has to be called this way. */
Stuff getStuff(Request request) {
Stuff stuff = new Stuff();
for(handleRepeat(request)) {
stuff.add(reallyGetStuff(request))
}
return stuff;
}
Stuff reallyGetStuff(Request request) {
logRequest(request);
Stuff stuff = reallyReallyGetStuff(request)
logStuff(stuff);
return stuff
}
Stuff reallyReallyGetStuff(Request request) {
Stuff stuff = reallyReallyReallyGetStuff(request)
executeCallbacks(stuff);
return stuff;
}
Stuff reallyReallyReallyGetStuff(Request request) {
if (request.isFoo()) {
return getFooStuff()
} else {
return getBarStuff()
}
}
Calling them handleRepeatAndLogAndExecuteCallbacksAndGetStuff, logAndExecuteCallbacksAndGetStuff, executeCallbacksAndGetStuff, and getStuff would be more correct, but is obviously unacceptable.
Here is a single-function version. More readable at this scale, but not scalable at all. It mixes 5 different responsibilities (repeats, logs, callbacks, foo/bar split, and Stuff aggregation), which is the opposite of clean code.
Stuff getStuff(Request request) {
Stuff result = new Stuff();
for(Request singleRequest : handleRepeat(request)) {
logRequest(singleRequest);
if (singleRequest.isFoo()) {
stuff = getFooStuff(singleRequest);
} else {
stuff = getBarStuff(singleRequest);
}
handleCallbacks(stuff);
logStuff(stuff);
result.add(stuff);
}
return stuff;
}
Here is the core part of a functional version. Note that the logging is split in two parts, I can't log the duration anymore for example.
Stuff getStuff(Request request) {
return new Stuff(handleRepeat(request).stream()
.peek(StuffReader::logRequest)
.map(StuffReader::getSpecificStuff)
.peek(StuffReader::handleCallback)
.peek(StuffReader::logStuff)
.collect(Collectors.toList()));
}
Is there a way to do organize this code closer to what the first example is doing but with a better naming? Or could you suggest any alternative solution where each method only has one responsibility and the result is still sensible and clean?
If you are dividing the method into smaller methods, each one with its responsibility (which is always a good idea) , that means that each method does a different thing. So, just adding really to its name one or many times doesn't match the content of the method.
You said you cannot do it in one method because violating SRP due to doing different things like repeats, logs, callbacks, foo/bar split, and Stuff aggregation. So, each method should be called accordingly:
repeats iterateOverElemtns(...)
logs logRequest(...)
callbacks applyCallbacks(...)
foo/bar foo() bar()
split reduceProblem(...)
Stuff aggregation aggregateResults(...)
Actually the first single method looks pretty clean to me, I just could extract the if:
Stuff getStuff(Request request) {
Stuff result = new Stuff();
for(Request singleRequest : handleRepeat(request)) {
logRequest(singleRequest);
applyFooBarLogic();
handleCallbacks(stuff);
logStuff(stuff);
result.add(stuff);
}
return stuff;
}
This is really clean code. You are overengineering in the first block. In the logRequest() just log the request, in the handleCallbacks(...) just handle callbacks, and so on. The getStuff(...) api method is the orchestrator, the high level action. Every business action (with one name) can be divided in smaller actions, with more specific names in a one deeper level of abstraction. If the getStuff is the higher abstraction naming, you should not use the name getStuff in the lower level.
To use an every day example, imagine you have a method eat(), that could be divided in putFoodInTheMouth(), chewFood(), swallowFood() and so on. You won't name those methods as eat(), reallyEat(), reallyReallyEat(). It's all about abstraction levels.
How about something like this:
abstract class RequestHandler<T> {
abstract T handleRequest(Request request);
}
public class StuffHandler extends RequestHandler<Stuff> {
Stuff handleRequest(Request request) {
// Do first thing
getStuff(request)
reallyGetStuff(request)
reallyReallyGetStuff(request)
reallyReallyReallyGetStuff(request)
}
// private doStuff / reallyDoStuff methods or whatever this particular handler needs to do
private Stuff getStuff(Request request) { ... }
private Stuff reallyGetStuff(Request request) { ... }
private Stuff reallyReallyGetStuff(Request request) { ... }
private Stuff reallyReallyReallyGetStuff(Request request) { ... }
}
this is clean. each individual handler is "clean" when observed from outside, and has only one responsibility - handling his thing. How it handles it, however, up to you, but there is a way to make this convoluted thing clean as well.
But i believe, once this abstraction is in place, that cleaning up individual methods of individual handlers will become easier; and becomes less of a factor. Some handlers will be simple, some others like this one might still be convoluted; but from the outside it's just a single thing with a single responsibility. Internal handler's implementation becomes a less important thing, as cleaning up (and dividing/following the "single responsibility principle" is scoped to just that particular handler)
Of course, you get additional bonus points by making the abstract handleRequest method have an abstract implementation that satisfies most cases, and leave the edge-case handlers to separate out the convoluted logic into new methods.
At this point, you'll definitely know whether just one abstract RequestHandler is enough, or you need more, e.g.
abstract ConvolutedRequestHandler<T> extends RequestHandler<T> {
T handleRequest(Request request) {
// figure out how to "standardize" this convolution
logAndRequestStuff(request)
T stuff = getStuffFromRequest(request)
return stuff.getFooOrBarStuff(request)
}
// offer additional abstract methods that these convoluted handlers will need
abstract logRequestAndStuff(Request request)
abstract T getStuffFromRequest(Request request)
abstract T getFooOrBarStuff(Request request)
}
abstract TypicalRequestHandler<TypicalThing> extends RequestHandler<TypicalThing> {
TypicalThing handleRequest(Request request) {
// call into RequestHandler::handleRequest which catches most cases fine
super.handleRequest(request)
}
this is roughly modeled on your rough example, so it makes as much sense as the original code you posted.
But the idea is to generally get rid of getFooOrBarStuff method, and just use an appropriate handler for each of the requests. Ideally, fetch (or have a factory) for the appropriate Handler for each of the request-types you have.
and externally, just do this:
RequestHandlerFactory<T> factory = new RequestHandlerFactory<T>();
// getClass() here referring to the Request / RequestThing or even the thing that drives the request handlers themselves
T requestHandler = factory.buildRequestHandlerFor(getClass());
? handlerResult = requestHandler.handleRequest(request)
but that really depends on what you pick your generic argument to be, whether the type of request, the type of the request's return value, or you know.

Figuring which design pattern to use?

In most radio devices, we can configure the wave which we want to explore and listen to stations using the demodulation mode compatible with this type.
There are at least two types AM and FM. We can model the radio device in this case as the following:
class RadioDevice {
void demodulate (String m) {
if(m.equals("FM")
/* FM modelation */
else if(m.equals("AM")
/* AM modelation */
}
}
How can I apply the strategy pattern in this case?
Why don't you use polymorphism ?
Make an interface:
interface Radio {
void modulate();
}
And than implement 2 classes:
FMRadio implements Radio{
public void demodule(){
//FM modulation
}
}
AMRadio implements Radio{
public void demodule(){
//AM modulation
}
}
And than, in your main, you could go:
Radio myRadio = new FMRadio();
myRadio.demodule();
If you can have an interface that covers the contract for both AM and FM demodulation, you could use the Strategy pattern:
Demodulator d; // interface Demodulator { byte[] demodulate(); }
switch(m) {
case "AM":
d = new AMDemodulator();
break;
case "FM"
d = new FMDemodulator();
break;
default:
throw new IllegalArgumentException("Unsupported type '"+ m + "'"); // you could use an Enum instead of a String
}
d.demodulate(waves);
This allows you to switch the Demodulator part on the fly while keeping the rest of the program logic in common (no duplication).
Check this repo (not mine) for design patterns and examples: https://github.com/iluwatar/java-design-patterns
To make it a proper Strategy pattern, I would add using a Context class to the previous answer of #Ladislav_M, that will wrap & encapsulate executing a particular strategy and give more flexibility to the code:
class Context {
private Radio radio;
public Context(Radio radio) {
this.radio = radio;
}
public Object runStrategy() {
radio.demodulate();
// do any other stuff you want
return ...
}
}
The execution in main would become more convenient:
Context context = new Context(new FmRadio());
Object result = context.runStrategy();
Or you can inline the above:
Object result = (new Context(new FmRadio())).runStrategy();
Of course, you can choose the implementation of Radio in a switch block and just pass it as a variable to the Context's constructor.
This is not a good use case for Strategy design pattern, its simple inheritance case. Strategy is used where the state of the object does not change but different algorithms apply at different times. e.g. Paypackage computation for different roles of employees (e.g. Temporary, Permanent etc.). Important point here is Temporary employee can become Permanent one day.
In the above case AM will never become FM in its life time. hence Strategy is not right pattern for it. These are (probably) different classes with common behavior (if present) can be shifted to base class. If they show a common contract with clients then even interface will do the task.

Web Service Return Function Specification Instead of Object?

Apologies if this question is a duplicate (or if it has an obvious answer that I'm missing) -->
Is there a practice or pattern that involves a web service returning a function definition to the client, instead of a value or object?
For an extra rough outlining example:
I'm interested in the results of some statistical model. I have a dataset of 100,000 objects of class ClientSideClass.
The statistical model sits on a server, where it has to have constant access to a large database and be re-calibrated/re-estimated frequently.
The statistical model takes some mathematical form, like RESULT = function(ClientSideClass) = AX + BY + anotherFunction(List(Z))
The service in question takes requests that have a ClientSideClass object, performs the calculation using the most recent statistical model, and then returns a result object of class ModelResultClass.
In pseudo OOP (again, sorry for the gnarly example) :
My program as a client :
static void main() {
/* assume that this assignment is meaningful and that all
the objects in allTheThings have the same identifying kerjigger */
SomeIdentifier id = new SomeIdentifier("kerjigger");
ClientSideClass[100000] allTheThings = GrabThoseThings(id);
for (ClientSideClass c : allTheThings) {
ModelResult mr = Service.ServerSideMethod(c);
// more interesting things
}
}
With my client side class :
ClientSideClass {
SomeIdentifier ID {}
int A {}
double[] B {}
HashTable<String,SomeSimpleClass> SomeHash {}
}
On the server, my main service :
Service {
HashTable<SomeIdentifier,ModelClass> currentModels {}
ModelClass GetCurrentModel(SomeIdentifier id) {
return currentModels.get(id);
}
ModelResultClass ServerSideMethod(ClientSideClass clientObject) {
ModelClass mc = GetCurrentModel(clientObject.ID);
return mc.Calculate(clientObject);
}
}
ModelClass {
FormulaClass ModelFormula {}
ModelResultClass Calculate(ClientSideClass clientObject) {
// apply formula to client object in whatever way
ModelResult mr = ModelFormula.Execute(clientObject);
return mr;
}
}
FormulaClass {
/* no idea what this would look like, just assume
that it is mutable and can change when the model
is updated */
ModelResultClass Execute(clientObject) {
/* do whatever operations on the client object
to get the forecast result
!!! this method is mutable, it could change in
functional form and/or parameter values */
return someResult;
}
}
This form results in a lot of network chatter, and it seems like it could make parallel processing problematic because there's a potential bottleneck in the number of requests the server can process simultaneously and/or how blocking those calls might be.
In a contrasting form, instead of returning a result object, could the service return a function specification? I'm thinking along the lines of a Lisp macro or an F# quotation or something. Those could be sent back to the client as simple text and then processed client-side, right?
So the ModelClass would instead look something like this? -->
ModelClass {
FormulaClass ModelFormula {}
String FunctionSpecification {
/* some algorithm to transform the current model form
to a recognizable text-formatted form */
string myFuncForm = FeelTheFunc();
return myFuncForm;
}
}
And the ServerSideMethod might look like this -->
String ServerSideMethod(SomeIdentifier id) {
ModelClass mc = GetCurrentModel(id);
return mc.FunctionSpecification;
}
As a client, I guess I would call the new service like this -->
static void main() {
/* assume that this assignment is meaningful and that all
the objects in allTheThings have the same identifier */
SomeIdentifier id = new SomeIdentifier("kerjigger");
ClientSideClass[100000] allTheThings = GrabThoseThings(id);
string functionSpec = Service.ServerSideMethod(id);
for (ClientSideClass c : allTheThings) {
ModelResult mr = SomeExecutionFramework.Execute(functionSpec, c);
}
}
This seems like an improvement in terms of cutting the network bottleneck, but it should also be readily modified so that it could be sped up by simply throwing threads at it.
Is this approach reasonable? Are there existing resources or frameworks that do this sort of thing or does anyone have experience with it? Specifically, I'm very interested in a use-case where an "interpretable" function can be utilized in a large web service that's written in an OO language (i.e. Java or C#).
I would be interested in specific implementation suggestions (e.g. use Clojure with a Java service or F# with a C#/WCF service) but I'd also be stoked on any general advice or insight.

Index Service Design - Sync / Async

I have a requirement to index items. This service should run Sync or Async.
I started designing an Interface
public interface IndexService{
public void index();
}
And two implementation, one for a Async Index:
public class AsyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}
And the other one to the Sync Index
public class SyncIndex implements IndexService {
public void index(){
//... Creates a Thread and index the items
}
}
But now there is another design that is having a IndexService, who has a flag to execute as a async service or as a sync service:
public interface IndexService{
public void index(int mode);
}
So now the implementation will know how to run base on that flag.
I know that the first design is better, but I need pros and cons to explain why.
I go for first approach because
1- code is cleaner AsyncInex class only has codes related to async call and syncIndex would has its own code.
2- you can avoid else if
...
public void runService(IndexService service) {
service.index()
}
// some where in your code
runService(new AsyncIndex());
// or
runService(new SyncIndex());
as you are working with interface "IndexService" you can always change implementation without changing clients code.
specially if you are using DI frameworks you can have the kick of it ;).
this is so important to not allowing client code know about the implementation. suppose situation where you are indexing, for instance, a database.
you want to do async index when data is huge or sync index when data is small.
caller should has no knowledge about the way Index is called. this way you can have different strategy in different situations without changing callers code. if you take the second approach you have to do some extra work.
I say both.
Assume, you plan to use the second approach. Your implmentation may look like:
public SyncOrAsyncIndex implements IndexService {
public void index(int mode) {
if(mode == 0) {
//sync processing code
} else if (mode == 1) {
//async procesisng code
}
}
That said, are you going to write all the implementation within this index method or SyncOrAsyncIndex class. That will possibly end up being unmanageable.
So, the index method may end up like this:
public void index(int mode) {
if(mode == 0) {
new SyncIndex().index(); //for example
} else if (mode == ) {
new AsyncIndex().index(); //for example
}
}
Assume, you decide on supporting a third mode. Imagine the plight of the index method or SyncOrAsyncIndex class. So, the first approach is needed.
So, as per "code to the interface" strategy the first approach is suggested. If the invoker is aware of the type of indexing, they can just instantiate the particular type and use it.
Else, along with the first approach the second one may be required as a factory or strategy to calculate which type of indexing to use based on the passed parameter. The invoker would then use the SyncIndex or AsyncIndex via SyncOrAsyncIndex.

Creating a simple String parser, Interactive Shell-like

I want to make a simple interative shell based on the console where I can write commands like login, help, et cetera.
I first thought of using Enums, but then I didn't know how to implement them neatly without a load of if-else statements, so I decided to go with an array-approach and came up with this:
public class Parser {
private static String[] opts = new String[] {"opt0", "opt1", "opt2", "opt3" ... }
public void parse(String text) {
for(int i = 0; i < opts.length; i++) {
if(text.matches(opts[i]) {
switch(i) {
case 0:
// Do something
case 1:
// Do something-something
case 2:
// Do something else
}
return;
}
}
}
}
But I ended up seeing that this was probably the most rudimentary way of doing something like this, and that there would be problems if I wanted to change the order of the options. How could I make a simpler parser? This way it would work, but it would also have said problems. The use of the program is purely educational, not intended for any serious thing.
A simple approach is to have a HashMap with the key equal to the command text and the value is an instance of class that handle this command. Assuming that the command handler class does not take arguments (but you can easily extend this) you can just use a Runnable instance.
Example code:
Runnable helpHandler = new Runnable() {
public void run(){
// handle the command
}
}
// Define all your command handlers
HashMap<String, Runnable> commandsMap = new HashMap<>(); // Java 7 syntax
commandsMap.put("help",helpHandler);
// Add all your command handlers instances
String cmd; // read the user input
Runnable handler;
if((handler = commandsMap.get(cmd)) != null) {
handler.run();
}
You can easily extend this approach to accept argument by implementing your own interface and subclass it. It is good to use variable arguments if you know the data type e.g. void execute(String ... args)
One solution that comes to mind is actually using Design patterns. You could use the input from the user, as the discriminator for a Factory class.
This factory class will generate an object, with an "execute" method, based on the input. This is called a Command object.
Then you can simply call the method of the object returned from the factory.
No need for a switch statement. If the object is null, then you know the user entered an invalid option, and it abstracts the decision logic away from your input parser.
Hopefully this will help :)

Categories

Resources