public interface IParam
{
}
public interface IProcessor<in T> where T : IParam
{
public void Apply(T param);
}
public class ConcreteProcessorA : IProcessor<ConcreteParamA>
public class ConcreteParamA : IParam
public class ConcreteProcessorB : IProcessor<ConcreteParamB>
public class ConcreteParamB : IParam
public class Provider
{
public List<IProcessor> _processors;
publick void Apply(IParam)
{
}
}
public interface IParam
{
}
public interface IProcessor
{ }
public interface IProcessor<in T>: IProcessor
where T : IParam
{
public void Apply(T param);
}
public class ConcreteProcessorA : IProcessor<ConcreteParamA>
{
public void Apply(ConcreteParamA param)
{
Console.WriteLine("Hello from processor A");
}
}
public class ConcreteParamA : IParam
{
}
public class ConcreteProcessorB : IProcessor<ConcreteParamB>
{
public void Apply(ConcreteParamB param)
{
Console.WriteLine("hello form ProcessorB");
}
}
public class ConcreteParamB : IParam
{
}
public class Provider
{
public Provider(IEnumerable<IProcessor> processors)
{
_processors = processors.ToList();
}
private List<IProcessor> _processors;
public void Apply<TParam>(TParam param) where TParam: IParam
{
foreach (var processor in _processors.Where(p => p
.GetType()
.GetInterfaces()
.Any(i => i.IsAssignableTo(typeof(IProcessor<TParam>))))
.Cast<IProcessor<TParam>>())
{
processor.Apply(param);
}
throw new InvalidOperationException("Для переданного типа нет обработчика");
}
}
public class Program
{
static void Main(string[] args)
{
var provider = new Provider(new IProcessor[]
{
new ConcreteProcessorA()
});
provider.Apply(new ConcreteParamA());
try
{
provider.Apply(new ConcreteParamB());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
Hello from processor Aзатем пишет исключение, т.к. обработчика не нашлось