As far as I understand your question (from the exchange of comments), some handlers can handle any type T(or many types T), while other handlers can handle only one type. In addition, you would like to use these processors within a single consumer polymorphically.
Here is what you can do:
:
public interface IHandler
{
T Process<T>(int process);
bool CanProcess<T>();
}
public interface IHandler<T>
{
T Process(int process);
}
IHandler<T> IHandler :
public class Adaptor<T> : IHandler
{
private readonly IHandler<T> handler;
public Adaptor(IHandler<T> handler)
{
this.handler = handler;
}
public T1 Process<T1>(int process)
{
if(!CanProcess<T1>())
throw new Exception(
"Contract violated. I cannot handle type " + typeof(T1).Name);
return (T1)(object)handler.Process(process);
}
public bool CanProcess<T1>()
{
return typeof (T1) == typeof (T);
}
}
- :
public class CompositeHandler : IHandler
{
private readonly IHandler[] handlers;
public CompositeHandler(params IHandler[] handlers)
{
this.handlers = handlers;
}
public T Process<T>(int process)
{
var handler = handlers.FirstOrDefault(h => h.CanProcess<T>());
if(handler == null)
throw new Exception(
"Contract violated. I cannot handle type " + typeof(T).Name);
return handler.Process<T>(process);
}
public bool CanProcess<T>()
{
return handlers.Any(h => h.CanProcess<T>());
}
}
IHandler<T> IHandler IHandler. , .
:
var service = new CompositeHandler(
new TypeThatImplementsTheNonGenericInterface(),
new Type2ThatImplementsTheNonGenericInterface(),
new Adaptor<SomeType>(
new TypeThatImplementsTheGenericInterface<SomeType>()));