I am a newbie and trying to understand concepts of inheritance and design patterns.
I came across this pattern http://en.wikipedia.org/wiki/Strategy_pattern when I w
The derived class is a base class. (That's the whole concept of inheritance: inheritance defines an 'is a' relationship).
Also, check out the Liskov substitution principle. :)
There is no casting needed, since ConcreteStrategyAdd is a Strategy - it satisfies all the requirements of being a Strategy. This is the principle of Polymorphism.
Perhaps a more simplistic example is needed:
abstract class Fruit { }
class Apple : Fruit { }
class Orange : Fruit { }
class Melon : Fruit { }
class FruitBasket
{
void Add(Fruit item) { ... }
}
FruitBasket basket = new FruitBasket();
basket.Add(new Apple()); // Apple IS A fruit
basket.Add(new Orange()); // Orange IS A fruit
basket.Add(new Melon()); // Melon IS A fruit
class Potato : Vegetable { }
basket.Add(new Potato()); // ERROR! Potato IS NOT A fruit.
Put really simply:
A Derived class (or subclass) is an instance of its base class.
So, when you pass an instance of ConcreteStrategyAdd into the constructor, you are essentially passing a Strategy object in.
There is no casting involved. The type hierarchy allows for this type of programming. It allows programmers to use polymorphism in their code.
its easier to understand if you use a more simplistic example than the strategy pattern.
suppose you have a class called "Fruit" and a class called "Apple" that derives from fruit. any method that is written to work with Fruit in general can work just fine with an Apple or any other specific type of fruit