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

Code & Comments from the Video


public class Animal {
	private String name;
	private double height;
	private int weight;
	private String favFood;
	private double speed;
	private String sound;
	// Instead of using an interface in a traditional way
	// we use an instance variable that is a subclass
	// of the Flys interface.
	// Animal doesn't care what flyingType does, it just
	// knows the behavior is available to its subclasses
	// This is known as Composition : Instead of inheriting
	// an ability through inheritance the class is composed
	// with Objects with the right ability
	// Composition allows you to change the capabilities of 
	// objects at run time!
	public Flys flyingType;
	public void setName(String newName){ name = newName; }
	public String getName(){ return name; }
	public void setHeight(double newHeight){ height = newHeight; }
	public double getHeight(){ return height; }
	public void setWeight(int newWeight){ 
		if (newWeight > 0){
			weight = newWeight; 
		} else {
			System.out.println("Weight must be bigger than 0");
	public double getWeight(){ return weight; }
	public void setFavFood(String newFavFood){ favFood = newFavFood; }
	public String getFavFood(){ return favFood; }
	public void setSpeed(double newSpeed){ speed = newSpeed; }
	public double getSpeed(){ return speed; }
	public void setSound(String newSound){ sound = newSound; }
	public String getSound(){ return sound; }
	/* BAD
	* You don't want to add methods to the super class.
	* You need to separate what is different between subclasses
	* and the super class
	public void fly(){
		System.out.println("I'm flying");
	// Animal pushes off the responsibility for flying to flyingType
	public String tryToFly(){
	// If you want to be able to change the flyingType dynamically
	// add the following method
	public void setFlyingAbility(Flys newFlyType){
		flyingType = newFlyType;


public class Dog extends Animal{
	public void digHole(){
		System.out.println("Dug a hole");
	public Dog(){
		// We set the Flys interface polymorphically
		// This sets the behavior as a non-flying Animal
		flyingType = new CantFly();
	/* BAD
	* You could override the fly method, but we are breaking
	* the rule that we need to abstract what is different to 
	* the subclasses
	public void fly(){
		System.out.println("I can't fly");


public class Bird extends Animal{
	// The constructor initializes all objects
	public Bird(){
		// We set the Flys interface polymorphically
		// This sets the behavior as a non-flying Animal
		flyingType = new ItFlys();


// The interface is implemented by many other
// subclasses that allow for many types of flying
// without effecting Animal, or Flys.

// Classes that implement new Flys interface
// subclasses can allow other classes to use
// that code eliminating code duplication

// I'm decoupling : encapsulating the concept that varies

public interface Flys {
   String fly();

// Class used if the Animal can fly

class ItFlys implements Flys{

	public String fly() {
		return "Flying High";

//Class used if the Animal can't fly

class CantFly implements Flys{

	public String fly() {
		return "I can't fly";


public class AnimalPlay{
	public static void main(String[] args){
		Animal sparky = new Dog();
		Animal tweety = new Bird();
		System.out.println("Dog: " + sparky.tryToFly());
		System.out.println("Bird: " + tweety.tryToFly());
		// This allows dynamic changes for flyingType
		sparky.setFlyingAbility(new ItFlys());
		System.out.println("Dog: " + sparky.tryToFly());

113 Responses to “Strategy Design Pattern Tutorial”

  1. Saleh says:

    It is the first time I encounter this design pattern which uses interface in a nice way.

    • admin says:

      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 🙂

  2. Thuy Nguyen says:

    You’re awesome! Thank you so much for your tutorials.

  3. Trini Allan says:

    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,

    • admin says:

      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

    • se7en says:

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

      • Minae says:

        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”.

  4. Jayant says:

    Thank you very much for the tutorials they are just awesome !!! Learnt them pretty fast.

  5. Jinil says:

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

  6. Venkatesh says:

    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 🙂

  7. DoubleYou says:

    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 ( but i had the feeling it was Aggregation? I find it hard to tell the difference. (I know about there definitions)

    • Derek Banas says:

      Thank you 🙂 yes I misspoke and you are correct. Most people just refer to everything as composition, but you understand the difference.

      • DoubleYou says:

        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!

  8. Hoang Edward says:

    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.

  9. Joe Contreras says:

    Great Video.


    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

  10. DanMan says:

    I’m confused.. how does the Animal class know about Flys.. maybe I need to watch the video again.

  11. Vivek says:

    Great stuff ! Thanks

  12. Radhika says:

    Thank you so much for your time and effort! 🙂 This really helps!

  13. Phoenix says:

    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?

    • Derek Banas says:

      Thank you 🙂 If by doing that you are increasing coupling, then that should be avoided. i hope that helps

      • Phoenix says:


        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?

        • Derek Banas says:

          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.

  14. Muhammad says:

    Thanks for this perfect tutorial, and for your effort.

  15. Anuj says:

    amazing explanation…. 🙂 Thanx 🙂

  16. Prasanna says:

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

  17. Srinivasan says:

    Great Tutorial Brian. Thanks a lot!

  18. Ariel says:

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

  19. Chow says:

    Great stuff, sir. Awesome voice too!

  20. Rey says:

    Great tutorial. Thanks for sharing your wisdom.

  21. Rajesh H says:

    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

  22. varanak says:

    Awesome work !

  23. da Hacedor says:

    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.

  24. I’m working through memorizing every design pattern I can and you’ve made it that much easier. I really appreciate the work on the videos. Thank you!

  25. Stas says:

    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?

  26. Badhri says:

    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!…

  27. Sriram says:

    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 🙂

  28. Marc-André says:

    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!

  29. Tirtha Chakraborty says:

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

  30. shiva says:

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

  31. weldu Hashenge says:


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

    • Derek Banas says:

      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

  32. Sarunas says:

    I have only one word for you: YourTutorialsAreGreat!! Keep it up. I’m going to watch all of them..

  33. Anonymous says:

    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?

  34. Sam says:

    Thanks for the videos. Great job Derek!

  35. Pradeep says:

    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.


  36. Asi says:

    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!

  37. Martin Gwarada says:

    Derek, thank you buddy. You are the best!!!

  38. Don Cooper says:

    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!

    • Derek Banas says:

      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.

      • Don Cooper says:


        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 on the Strategy pattern page (, 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.

        • Derek Banas says:

          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 🙂

  39. Andrea lee says:

    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.

    • Derek Banas says:

      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;
      14 if (newShipType.equals(“U”)){
      16 return new UFOEnemyShip();
      18 } else
      20 if (newShipType.equals(“R”)){
      22 return new RocketEnemyShip();
      24 } else
      26 if (newShipType.equals(“B”)){
      28 return new BigUFOEnemyShip();
      30 } else return null;
      – See more at:

      I hope that helps 🙂

      • Andrea lee says:

        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?

        • Derek Banas says:

          Most patterns have the same goal which is to add flexibility or to streamline the code. They can very often be used interchangeably.

          • Andrea lee says:

            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

            • Derek Banas says:

              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.

  40. Sandeep says:

    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

  41. Anon says:

    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 🙂

  42. Karthick says:

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

  43. Sunil says:

    Awesome tutorial, Clearly described. Thanks a lot for your videos.

  44. zal says:

    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 🙂

  45. Raf says:

    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?

  46. Pratik Prasad says:

    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

  47. Mazen says:

    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 🙂

  48. Nick says:

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

  49. Denis says:

    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).

  50. Mostafa says:

    Banas for president,

    Thank you for your help

  51. David N. says:

    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 to Anonymous Cancel reply

Your email address will not be published.