Strategy Design Pattern Tutorial

Strategy Design Pattern TutorialHere is my Strategy design patterns tutorial. You use this pattern if you need to dynamically change an algorithm used by an object at run time. Don’t worry, just watch the video and you’ll get it.

The pattern also allows you to eliminate code duplication. It separates behavior from super and subclasses. It is a super design pattern and is often the first one taught.

All of the code follows the video to help you learn.

If you liked this video, tell Google so more people can see it [googleplusone]

Sharing is nice [nttfblike]

Code & Comments from the Video

ANIMAL.JAVA

DOG.JAVA

BIRD.JAVA

FLYS.JAVA

ANIMALPLAY.JAVA

113 thoughts on “Strategy Design Pattern Tutorial”

    1. I’m glad to hear that. I’ll cover many more. If you are into thinking about building great software, you’ll love the tutorials I make over the next few months 🙂

  1. Your tutorials are pretty awesome, the best stuff I’ve seen on youtube hands down…, anyway thanks alot for taking the time to post. I am dutifully reviewing the code as you recommended and I came across something I wasn’t sure of…

    In the comments line above you mention the following:

    // without effecting Animal, or Flys.

    Not sure if it is my novice thinking or not, but wanted to know if “effecting” or “affecting” was the word intended here.

    Thanks for clarifying,
    Allan.

    1. Thank you very much 🙂 I do my best to make the best videos I can. In regards to your question, honestly I don’t know the difference between the two words. I’m really good at a few things, but grammar has never been my strong point. Sorry about that

    2. Alan, it’s clearly “effecting” meaning – “to have consequence”
      Derek was right the first time, maybe you should look up “pedantic” 🙂

      1. Actually, “affecting” would be right in this case.

        “Effecting” means to bring about, or to cause/create . Affecting means to influence, or to cause/create a change in . You are not bringing Animal about. You are causing a change in Animal. If you wanted to use “effecting”, you could, but you would have to say it like this: “without effecting a change in Animal”.

  2. Nice tutorials. I think, the best video tutorials I have ever seen in YouTube. Thank you so much boss. 🙂 Keep up the good work.

  3. Thank you for the awesome videos on design pattern. well done!!!
    You have done amazing videos and very simple to understand with the code. Thanks a lot 🙂

  4. First of all; great tutorials!!

    Watched most of the design patterns. Had just one question about the explanation at this pattern. You’re talking about Composition (Animal.java) but i had the feeling it was Aggregation? I find it hard to tell the difference. (I know about there definitions)

      1. Thank you for the quick reply!!

        it was probably…. you….that had told me the differences in some tutorial ;). i’ll continue with the refactoring tutorials and i am looking forward to the upcoming Android tuts! Your videos are easy to follow and nicely backed by the code on the website. Amazing job!

  5. Firstly, thanks for your great video and enclosed source code, but I also have a question for you:
    Why don’t you encapsulate the flyingType field in the Animal class with protected modifier so that the sub-classes can directly access to this field but the clients can’t, they must use the setFlyingAbility method instead.

  6. Great Video.

    Question:

    I want to design an object for exporting a file to XLS; CSV; Word in ASP.NET. They have the same properties but have different values. The initial reaction is to use a Switch statement which breaks the Open-Close principle. However I don’t want to create an object for each export type during implementation. Instead I want to take the value from the button click event for the export process and using that value create a reference that evaluates the value being passed and determine which object to retrieve like an XLS export object; CSV export etc.

    Feedback on design would be great

  7. Hello Derek,

    Very good explanation of Strategy Design Pattern. I have one question regarding this. Can strategy class have access to members of animal class? If yes how should animal class access should be given to strategy class?

      1. Darek,

        In my application I need access members of Animal class in strategy class? I am planning to use interface which gives only few members access to strategy. Is it good for avoiding coupling or need to something else?

        1. I may not be understanding the question. The strategy pattern is used to separate behavior from the super and subclasses. So, it would defeat the point if they communicated directly with each other.

  8. Very good explanation. I really liked the way you presented the patterns. Keep up the good work Sir.

  9. Congratulations. This is the firt video I watched, and now I will carry on watching all the rest. Great staff!

  10. Hi Derek,

    These days I am working n C# and I had used Java around 7 years back in my college days, but you explained things with such a beauty that it helped me a lot.

    Hats off to you… Excellent Job
    I am a fan of yours… Cheers

  11. I’ve just started with design patterns. To begin with, I was told by my friends to start with some book but after going through first four videos on your youtube channel, I have cancelled the order for that book. I find this sufficient enough to start implementing the patterns.
    Thanks for all the stuff. And, please accept my congratulations for the same.

  12. Great video!
    I’ve started reading some book about Design Patterns, but it is lack of simple examples as you show in your tutorials!

    would it make any difference, if I would make the Fly interface as an abstract class & ItsFly,CantFly as derived classes of Fly?

  13. Awesome!… I referred multiple examples but I was not able to understand the real benefit of this pattern. But your video gave me a very clear and thorough understanding. Great work and thanks for all your effort on this!…

  14. Well, this is so much better than reading those theoretical books which do not give much insight into the code. The best tutorial for sure! Thanks 🙂

  15. Waw! Another great video!

    I got a final exam tommorow at 9 and you did a tutorial about every pattern we have covered during the semester !
    Definetly the most effective study method i’ve used in many years!

    Thanks again to use those simple examples, every teacher should be like you!

  16. Your explanation and so easy to remember technique is something that can’t be thanked enough. Thanks a lottt..

  17. hey Thanks for bringing up this tutorial,it is very easy to understand, I liked it now i can learn design pattern very fast.

  18. Sir,

    I was wondering how the Animal.java know about the Flys interface???I could n’t understand how they are related….
    Thank you for clarifying

    1. Take a look at this line

      // Composition allows you to change the capabilities of objects at run time
      public Flys flyingType;

      The Flys object is stored in every Animal. It can then be changed if needed without disturbing the code

  19. Thanks for the videos. Great job Derek!
    Code is very helpful in understanding the design patterns. It will be very helpful if we can download the slides as well. They have some very important information such as when to use particular design pattern. If they are available for download, can you please share the link?
    Thanks

  20. Thanks for the videos. Great job Derek!
    Code is very helpful in understanding the design patterns. It will be very helpful if we can download the slides as well. They have some very important information such as when to use particular design pattern. If they are available for download, can you please share the link?
    Thanks

  21. I have started design pattern series, Thanks Derek.
    Now I am clear on Strategy pattern, I have just one question.
    What is Association and Aggregation, and what is difference between these with Composition.

    Thanks
    Pradeep

      1. Thanks Derek,The diagram helps lot, Now clear on Association, Aggregation and Composition 🙂 .

        Thanks
        Pradeep

  22. Hi Derek,
    thank you very much for your amazing videos… I’m learning so much thank to you.. i just can’t tell you how glad I am for came across your videos!

  23. Very good series! You are truly demystifying an important topic. Above, in the comments here to the Strategy Pattern, you say, “The strategy pattern is used to separate behavior from the super and subclasses.” With that one sentence, I finally clearly understood the purpose of it. Often, with design patterns, teachers focus get lost in explaining the mechanics, and the reason-to-use gets lost in the wash of information. Can you make a list of these kinds succinct formulations, and post them on your site? ie, one sentence per each design pattern. I think for certain patterns, like Strategy, the “why” is not obvious whereas the mechanics are simple. I would truly appreciate it if you focused like a laser on the why’s, so that we know when to use a given pattern. And, as you do in your video, please state the why’s in different ways (perhaps two or more sentences instead of one) so that the clarification may come from different angles.

    Thanks again for your excellent efforts!

    1. Thank you 🙂 It is always great to hear that I was able to clear everything up for people. I’ll see what I can do about that list. These tutorials became popular many months after I originally posted them, so I stopped short of making a video like you requested. I’ll see what i can do now.

      1. Derek,

        Glad to hear! I will look forward to that list very much.

        I was thinking of a more complete sentence to describe the Strategy pattern, “The strategy pattern is used to separate behavior from the super and subclasses, when you want to invoke this dissimilar behavior with the same function in the client (making use of polymorphism).” Also, I was reading http://oodesign.com on the Strategy pattern page (http://oodesign.co/strategy-pattern.html), and it says there that the Strategy pattern and the Bridge pattern have the same UML diagram, “but differ in their intent”. Again, another example of the teacher being clear on the easy stuff (mechanics/structure) but using jargon, almost maniacally trying to keep secret the main point: why. Why would you use one or the other? This is where the esoteric side of design patterns starts to lose us regular coders who are not academics, but simply want to write better code. The jargon starts to get too thick, and the reasons for using a particular pattern are obscured. We want credible examples and, more importantly, scenarios indicating when a given pattern is appropriate.

        Thanks for listening to my mini rant.

        1. I’ll try to explain them in simple terms.

          The Bridge Pattern allows you to create 2 types of abstract objects that can interact with each other in numerous extendable ways. In my bridge design pattern example I created a way for an infinite variety of remote controls to interact with an infinite variety of different devices.

          The strategy pattern allows you to change what an object can do while the program is running. In my strategy design pattern example I showed how you can add an object that represents whether an Animal can fly or not to the Animal class. This attribute was then added to every class that extended from Animal. Then at run time I was able to decide if an Animal could fly or not.

          I hope that helps 🙂

  24. I am a little bit confused on the use of strategy and factory both created at runtime. Kindly please elaborate the difference.
    Thank you in advance and I love your videos.

    1. In my strategy design pattern tutorial I demonstrated how you can at run time give any Animal subclass the ability to fly.

      1. I added the Flys object to Animal which all subclasses then receive with : public Flys flyingType;

      2. ItFlys and CantFly implement the Flys interface

      3. At runtime I can change the version of Flys : sparky.setFlyingAbility(new ItFlys());

      4. Now sparky can fly

      With the Factory pattern tutorial I showed how the EnemyShipFactory pops out a different type of ship based off of user input :

      EnemyShip newShip = null;
      13
      14 if (newShipType.equals(“U”)){
      15
      16 return new UFOEnemyShip();
      17
      18 } else
      19
      20 if (newShipType.equals(“R”)){
      21
      22 return new RocketEnemyShip();
      23
      24 } else
      25
      26 if (newShipType.equals(“B”)){
      27
      28 return new BigUFOEnemyShip();
      29
      30 } else return null;
      – See more at: http://www.newthinktank.com/2012/09/factory-design-pattern-tutorial/#sthash.aTZJT3zG.dpuf

      I hope that helps 🙂

      1. Thank you for your explanation. I have another question if you don’t mind. Why some examples use factory in calculator program and others use strategy?

          1. Thank you very much. For almost 12 hours I have been going back and forth to understanding strategy n factory. They are almost closely the same even their uml.
            Your video are good and I also like the code refactoring.

            When are you going to start j2ee, spring, hibernate…..I guess many are eager for those videos. I hope soon and hopefully it will happen this year

            1. You’re very welcome 🙂 Before Java Enterprise I want to make an Android tutorial that teaches everything in a format in which anyone will be able to make any Android app they can imagine. Sorry it is taking so long, but I’m very serious about teaching Android right now.

  25. You are like the best Tutor I’ve ever seen. The quality of the lessons and the way you teach is amazing. Thanks a ton

  26. Hi, our professor taught us this pattern but I still don’t get on how do I access the dog digHole() method if I used the class Animal other than forcing it.

    ((Dog) Sparky).digHole(); which is not appropriate 🙂

    1. I’m confused. That code you have there does work. You wouldn’t have to cast it though if you had the original method in the super class though.

  27. Great video and awesome teaching!! Thanks a lot for taking the effort and making things very interesting 😀

  28. Hey Derek! I have been watching most of your OOP videos. well, I am not proud of myself for not having the courtesy to thank you until now.
    you r an amazing teacher. I will soon convert all the code you used in Design Pattern videos into Php and put on github. I will let u know when I finish 🙂

  29. Hello Derek,

    Thank you for these videos they are very informative and helpful.

    Can you please explain to me why you have the flyingType variable is public? If it is public why do you need the setter method?

  30. Really really nice tutorials, I love watching your tutorials on Design Patterns, I have planned that I’ll watch all of your tutorials on youtube.
    Thanks a lot for all the tutorials 🙂

    Can you please tell me the screencasting software you used to create these tutorials

  31. would be really nice if you redo the videos in C#. I understand that most concept are the same but still better for and for a whole lot of newbies. thank you so much for videos, really great stuff although you are talking little bit fast 🙂

  32. As a current Design Patterns student going through Head First Design Patterns, your videos are a helpful reinforcement. Thanks!

  33. Thanks! This videos are many times more interesting for me, that the booring books and lectures))) In addition, it helps to learn English (it’s not my native language).

  34. What if you just had an interface Flys, and have Bird implement it. Can you elaborate on why this option is duplicate code, and not good. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *