Strategy Pattern with Different parameters in interface (C#)

user210757 picture user210757 · Dec 24, 2009 · Viewed 13.1k times · Source

I am basically trying to implement a Strategy pattern, but I want to pass different parameters to the "interfaces" implementation (that inherit from the same object) and don't know if this is possible. Maybe I'm choosing the wrong pattern, I get an error similar to

'StrategyA' does not implement inherited abstract member 'void DoSomething(BaseObject)'

with the code below:

abstract class Strategy
{
 public abstract void DoSomething(BaseObject object);
}

class StrategyA : Strategy
{
 public override void DoSomething(ObjectA objectA)
 {
  // . . .
 }
}

class StrategyB : Strategy
{
 public override void DoSomething(ObjectB objectB)
 {
  // . . .
 }
}

abstract class BaseObject
{
}

class ObjectA : BaseObject
{
 // add to BaseObject
}

class ObjectB : BaseObject
{
 // add to BaseObject
}

class Context
{
   private Strategy _strategy;

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

    // i may lose addtions to BaseObject doing this "downcasting" anyways?
 public void ContextInterface(BaseObject obj) 
 {
  _strategy.DoSomething(obj);
 }

}

Answer

Reed Copsey picture Reed Copsey · Dec 24, 2009

It sounds like you're actually trying to reinvent the Visitor pattern, instead of just using the Strategy pattern the way it was intended.

Also, since you're using C#, I'd recommend reading Judith Bishop's paper titled On the Efficiency of Design Patterns Implemented in C# 3.0. This covers multiple approaches to the visitor pattern in detail, and has some interesting, related useful ideas.