Alex Rivera | Logout

Passing Derived class as a parameter to a method when the parameter type is base class

Asked 2011-01-04T15:07:58.917
67

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 was going through some blog.

I found it interesting and wanted to learn more. So I developed the following program.

static void Main(string[] args)
{
    Context context;

    // Three contexts following different strategies
    context = new Context(new ConcreteStrategyAdd());
    int resultA = context.executeStrategy(3, 4);

    context = new Context(new ConcreteStrategySubtract());
    int resultB = context.executeStrategy(3, 4);

    context = new Context(new ConcreteStrategyMultiply());
    int resultC = context.executeStrategy(3, 4);

    Console.Read();
}      

abstract class Strategy
{
    public abstract int execute(int a, int b);

    public void Test()
    {
        Console.Write("tttt");
    }
}

class ConcreteStrategyAdd : Strategy
{
    public override int execute(int a, int b)
    {
        Console.WriteLine("Called ConcreteStrategyAdd's execute()");
        return a + b;  // Do an addition with a and b
    }
}

class ConcreteStrategySubtract : Strategy
{

    public override int execute(int a, int b)
    {
        Console.WriteLine("Called ConcreteStrategySubtract's execute()");
        return a - b;  // Do a subtraction with a and b
    }
}

class ConcreteStrategyMultiply : Strategy
{
    public override int execute(int a, int b)
    {
        Console.WriteLine("Called ConcreteStrategyMultiply's execute()");
        return a * b;   // Do a multiplication with a and b
    }
}

class Context
{
    private Strategy strategy;

    // Constructor
    public Context(Strategy strategy)
    {
        this.strategy = strategy;
    }

    public int executeStrategy(int a, int b)
    {
        return strategy.execute(a, b);
    }
}

The program compiles fine and is workin

Edit
Report

1 Answer

2

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

answered 2011-01-04T15:18:25.727

Your Answer