Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

If possible, ask for an instance of Sally:

class Jim 
{
    public Jim(Sally sally){ /* ... */ }
}

If, however, Jim needs to know WHEN to construct Sally, you can pass in a delegate:

class Jim
{
    private Func<Sally> _createSally.

    public Jim(Func<Sally> createSally)
    {
        _createSally = createSally;
    }

    public void ConsumeSally()
    {
        Sally sally = _createSally();
        /* ... */
    }
}

Simplest usage:

var jim = new Jim( () => new Sally() );

You don't need a class (Pat) to know how to instance sally, unless it really adds value to your code. Either way, you probably don't want Jim to know about Pat, so if Pat is needed this is what you'll want:

var jim = new Jim( () => Pat.GetSally() );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top