Hello programmers. This is the start of a series about Design Pattern. Design Patterns are a standard solution for problems you have to deal with every now and then. Especially object oriented programming (OOP) has shortcomings you need to handle somehow. The right pattern in the right situation will help to produce code that is easily maintainable, understandable and has a lesser change to produce bugs.
The Strategy Pattern
Inheritance
let's imagine we want a little bird simulation where we need every kind of bird behaviour. Our first idea might be to make an abstract class for bird that every sort of bird has to extend. Since we know that most birds can fly and swim, we implement those methods already. The method display is different for every bird, but has to be implemented by them, so we make it abstract.
Our first bird type is a dug, the second a swan. No problem with that. They can use the predefined swim() and fly() methods and only implement display().
Now we also want to add species like penguin, flamingo and ostrich. Those birds can not fly. Therefore they have to implement fly() to let it empty (if they inherit the default implementation they would be able to fly() which is wrong). The penguin is also capable of diving. I configure this as a different type of swimming, so we override this method too. An ostrich does not swim I think. This bird has to implement swim() and let it empty. The next problem is that it can run instead. So we need a new feature or skill for our birds: the method named run(). Now look at our diagram and say how many classes we have to change to implement the run() skill.
If we add 50 more birds like that implementing new skills will be a pain in the ass. Also we have a lot duplicated code, e.g. for all birds that can dive we override the swim method and implement the same code. That can not be a good solution. Let's think about another.
Interfaces
What if we use interfaces, so we don't need to implement so many empty methods?
Thx. Every programmer should be capable to understand UML. It is easier and more clear explaining concepts with it than with source code. But specifications are mostly no fun.