Search code examples
c#interfacedesign-patternscontract

Interface that contains a way to create an instance


I need a pattern:

I'm using C#.

Say there are three actors; Jim, Pat, and Sally. Pat's job is to create an interface as a contract between Jim and Sally. Sally's job is to create a class that implements the interface and Jim's job is to write a class that consumes Sally's object.

Jim should not know about Sally's concrete object, only that it implements the common interface.

Pat needs to include in the contract a way for Jim to create an instance of Sally's concrete object but referenced as the interface.

There is no way to include a static method definition in either an interface or abstract class, so you can't do something like:

public interface IFoo
{
    public static IFoo CreateIFoo();
}

How can Pat write the contract to guarantee that Sally will create a method for Jim to create her concrete object referenced as the interface?


Solution

  • Sounds like you need an abstract factory. In addition to IFoo, create an interface IFooFactory with the CreateFoo method. Give Jim an instance of an object that implements IFooFactory, and Jim would call the CreateFoo method. It could be either Sally or Pat's job to create the instance of the object that implements IFooFactory.