Home > Best Practices, Design Patterns, Learn This, Opinion, tutorial > Learn this: Strategy pattern vs Decorator pattern

Learn this: Strategy pattern vs Decorator pattern

As mentioned in a previous article, one thing I like to do when giving interviews is throwing out a curve ball. A standard type of questions I like to ask about are design patterns. Normally I will ask them to describe a specific pattern and seeing that both Strategy patterns and Decorator patterns are pretty common, I will ask about those. Most of the time, they can answer at least one of those. Whenever they answer both, I like to throw in the ‘Describe the difference between them and when you would use them.’

I ask this normally because it is kind of a gray area. Well maybe gray area isn’t the correct phrase, but they are strikingly similar*. They both encapsulate and delegate the behavior of the classes. They both encourage composition. Both are great alternatives to inheritance. And they both allow for new behaviors to be easily added to existing classes. With all the similarities, its hard to see where they differ, making it a great question to ask in an interview.

Before I get into the details, I would like to have a quick explanation of what they are. Well I am going to cheat for the strategy pattern because it was one of the first articles I wrote. Go take a read…
.
.
.
If you didn’t read the article, the run down allows you to swap out implementations of what specific components can do at run time via the use of interfaces. Also if you really didn’t read it, go read it.
.
.
.
Alright, as for the decorator pattern. It is extremely similar except for the fact that it not just allows you to swap out implementation at run time, but they allow you to build ON TOP of the behavior of your components. The way it works is a base class with a specific behavior. Then our decorator will be a class that we will use to change that behavior by extending the base class, as well as having that base class as a property on the component. In essence, the decorator extends and wraps the base class. Lets look at a short example of how a decorator works

For this example, lets think of a text formatter. We want something that will take a string and format it however which was we want. There will be a decorator will make a String all capitalized, another that will concatenate two strings, then another one that will replace the word “this” with “that”. Here is our abstract class:

public abstract class Text{
    public abstract String format(String s);
}

And here is our base decorator:

public abstract class TextDecorator extends Text{
    public abstract String format(String s);
}

As you can see, our decorators are just extensions of our abstract class and they will have their own format function attached to it. Now lets take a look at our base implementations.

For our main class, it will just be something rather generic.

public class BaseText extends Text{
    public BaseText(){
    }
    public String format(String s){
        return s;
    }
}

This class will just return its text property with out any changes to it. Next lets see some decorators we could create in order to change our text.

public class AllCaps extends TextDecorator{
    Text text;
    public AllCaps(Text text){
        this.text = text;
    }
    public String format(String s){
        return text.format(s).toUpperCase();
    }
}
public class StringConcat extends TextDecorator{
    Text text;
    public StringConcat(Text text){
        this.text = text;
    }
    public String format(String s){
        return text.format(s).concat(s);
    }
}
public class ReplaceThisWithThat extends TextDecorator{
    Text text;
    public ReplaceThisWithThat(Text text){
        this.text = text;
    }
    public String format(String s){
        return text.format(s).replaceAll("this","that");
    }
}

Alright so now we have our three decorators. Obviously there is very little real world value to these, but this is just for example sake. The magic is really in the format function. Each one of the decorators takes in a Text object with its constructor. The format function then calls its format function to get its text, then decorators it based off whatever that format function does. But how does this all tie together in the implementation class?

public class TextImpl{   
    public static void main(String args[]){
        Text t = new BaseText();
        Text t1 = new AllCaps(t);
        t1 = new StringConcat(t1);
        t1 = new ReplaceThisWithThat(t1);
        System.out.println(t1.format("this is some random text"));
    }
}

If you were to run this, you would get this output:

THIS IS SOME RANDOM TEXTthat is some random text

So what has happened? After we instantiated our base class, we then wrapped it, or “decorated” (funny how that works out) it, with our decorators. Then after we call the format function on this, it will before going through its decorators. In each format decorator, it will call its Text object’s format function, until it reaches an end. As it goes through, each decorator will perform its on specific task an then move onto the next.

That is how the decorator classes work. While it answers that question, it does not answer the question of ‘what is the difference between a decorator pattern and a strategy pattern?’ Well you might have been able to notice by now, but when you want to use a decorator, its usually a situation where you are going to have multiple attributes to an object that may or may not be used.

An example would be say something like a grid cell renderer. What if you wanted it your item renderers to make something bold. Another one would change color. Another would add a button to click. Another one would format a number, etc, etc, etc. You are either going to create one massive item renderer that you will have to maintain or create a class for each permutation of options, which adds up pretty quickly. With the decorator pattern, we can just create a decorator for each one of those and just wrap our item renderer.

Another good example is the dynamic filter component that was created in this article. A coworker of mine did an implementation of it using the decorator pattern. A situation like a filter component is perfect. We might need to filter on a date, a text input, etc. We can wrap our filtering work in multiple decorators to just go through it all.

Whats a good example of when to use a strategy pattern? The example I like to use is a logging system that you can change out which loggers are used at run time. Something like a strategy pattern works great here, because we don’t want to wrap something like this. There is no need to. This is a base implementation that is going to be used straight up. We aren’t going to add anything special to it. In this case, we have X amount of logger implementation (strategies), and when we want to change them, we do.

At this point, it boils down to when you want to use a multiple approaches to something, use a strategy pattern. When you want to create something where certain things may or may not be used to alter an object/component/whatever, then you should be using a decorator.

It can be confusing at times to tell the difference between them and when you would use one over the other. There are a lot of similarities that they share. Technically speaking, a lot of times, they can have the same out come. The choice of which to use obviously depends on your applications requirements. However, despite their similarities, they both still have their own specific place where they should be used.

Agree? Disagree? Think I left anything out? Feel free to comment.

If you want to check out the source, here you go!

*Note: There is also the state pattern, which is also strikingly similar. In fact, it pretty much does the same thing, but assigns them based on the state of your program.

Best Practices, Design Patterns, Learn This, Opinion, tutorial , , , ,

  1. May 11th, 2009 at 01:08 | #1

    If I were asked this in an interview, I’d point out that Strategy is Java’s pathetic attempt at The Expression Problem. I might also mention pattern matching and algebraic types. Then, I’d talk about how Decorator is a verbose means of newtyping to provide implementations of an interface or type-class for an isomorphic structure.

    Curious, how would you respond?

  2. boomi
    May 11th, 2009 at 02:49 | #2

    Somebody think of the labels! Those ‘Text text’ properties have two problems: They are not Text, and hey, they are not text either. Would it have been so bad to call that ‘TextFormatter base’ or something — anything — else than ‘Text text’? Like, say, ‘Foo bar’? That would cause way less confusion.

    You can’t educate people about design patterns when your code doesn’t even have proper labels.

    @Tony Morris:
    I’d respond by asking how this is relevant. (And add ‘* wanker’ to my notes, underlining it when you subsequently fail to demonstrate.)

  3. May 11th, 2009 at 03:42 | #3

    Very good article, I think that this question is a very good question to throw when interviewing candidates. thanks for sharing.

  4. May 11th, 2009 at 08:03 | #4

    I would probably be confused since I didnt mention java at all in the question and then further respond that the strategy pattern is not specific to java at all. I would also probably follow something similar to boomi’s response.

  5. May 11th, 2009 at 08:04 | #5

    noted :) good point.

    Thanks!

  6. Roger
    May 11th, 2009 at 08:34 | #6

    Hello,

    Which design patterns would you say are common enough to be asked during an interview? everytime i hit the books i get overwhelmed with all of the GO4 design patterns, i know you should know all of them, but, it’s hard to keep track of all of them, so it should be nice to just focus on those that are “essential” or common, that is, the ones that you must know or at least be familiar with.

  7. May 11th, 2009 at 08:46 | #7

    Strategy allows you to replace something with an alternative implementation. Decorator transparently enhances objects. There are several patterns in GoF that look pretty similar to each other but IMO these two are not among those.

  8. KL
    May 11th, 2009 at 11:42 | #8

    Great article! One thing that I’d add (while subtle) is the different “type” of design patterns that Strategy and Decorator are, which may shed light on how and when to use design patterns, in general.

    Stategy is a behavioral design pattern, meaning, you use it to describe or design how software components/layers interact with each other. This is usually the high level interfaces/abstract classes/object hierarchy.
    Decorator, on the other hand, is more of a structural design pattern. This deals more with concrete object implementation.

    In the article, it seems you are saying you have to choose to use one or the other, which I don’t think is necessarily correct. Since they happen at different levels of the architecture, they can be used together or separately.

    Just my 2 cents.

  9. May 11th, 2009 at 12:19 | #9

    @Roger
    90% of the time, I will ask about the Singleton pattern (the curve ball for this is to how to “properly” do it in actionscript). Decorators and Strategy patterns will usually get mentioned. More so on strategy since they deal with interfaces and I can easily roll into questions about that.

    There are a few others that might get mentioned, but they definitely get mentioned more so than the others.

    A really good book (despite its silly cover) is Head First Design Patterns They definitely hit on most of the popular patterns and do a great job at explaining them and providing examples.

    Hope that helps!
    Marcel

  10. John P
    December 16th, 2009 at 17:00 | #10

    A funny analogy in GoF is Decorator changes the skin, while Strategy changes the guts. I think this is a pretty relevant distinction.

  11. Cellux
    May 3rd, 2010 at 03:01 | #11

    I wouldn’t ask about specific patterns on an interview. Knowing a pattern in itself doesn’t give real value to a developer because it’s just a part of the story of modeling. I’ve come across a lot of developers who know most patterns of the Gang of Four if specifically asked but they simply don’t or can’t use them in practice.

    I think it’s better to do a “real” OO modeling excercise where using some patterns is advantageous to address the problem. Then you test the skill that’s most relevant to your business and you still have the option to talk about relevant patterns.

    What do you think?

  12. August 28th, 2010 at 21:09 | #12

    @Jose Noheda: awesome, that really boils it down.

    Thanks Marcel. I’m new to these patterns and although they may not be too similar to the experienced, I was pretty confused at first. This cleared it up :D

  13. Rahul
    September 15th, 2011 at 01:16 | #13

    Strategy : Use when u have a choose from multiple standalone approaches (algorithms to address certain issue)

    Decorator : Use when u have to choose from multiple approaches where each approach (may or may not) need to fabricated using certain thing in certain order.

    It will help to overcome the need to specialise various combinations using inheritance methodology.

  14. Mohit Jethva
    December 19th, 2011 at 07:02 | #14

    Very good example keep it up…………… :)

  1. No trackbacks yet.