Wednesday, February 2, 2011

Interfaces as object contexts

Here's a possibly useful idea I came up with a few weeks ago. I've come across situations where an object needs different behavior depending on the context or how it's used. Usually the state or strategy design pattern (or a mess of if statements) can handle this, but so can explicit interfaces in C#.

First make an interface for each set of behavior you want.

interface IContextA
{
  string Property { get; }
  int Method(int data);
}

interface IContextB
{
  string Property { get; }
  int Method(int data);
}

Then create the different contexts or scenarios using the interface with the behavior you want.

static void DoStuffInContextA(IContextA example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

static void DoStuffInContextB(IContextB example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

Then create a class that implements the different behavior.

class MultiContextObject : IContextA, IContextB
{
  string IContextA.Property
  {
    get { return "called in context a"; }
  }

  int IContextA.Method(int data)
  {
    return data + 1;
  }

  string IContextB.Property
  {
    get { return "called in context b"; }
  }

  int IContextB.Method(int data)
  {
    return data - 1;
  }
}

And now you can use interfaces to select which set of behavior you want your object to use.

static void ExplicitInterfaceAsContextTest()
{
  MultiContextObject example = new MultiContextObject();
  DoStuffInContextA(example);
  DoStuffInContextB(example);
}

I think this is neat. It won't replace state and strategy patterns, but there's probably cases where those aren't possible or where this would work better.

No comments:

Post a Comment