私は現在、IResponse を実装するオブジェクトを返す Chain of Responsibility を実装しています。
public interface IRequest
{
}
public interface IResponse
{
}
public interface IFactory
{
bool CanHandle(IRequest request);
IResponse HandleRequest(IRequest request);
}
public class Foo : IResponse
{
public void SpecificMethod()
{
Console.WriteLine("SpecificMethod() only belongs to Foo");
}
}
public class FooRequest : IRequest
{
}
public class FooFactory : IFactory
{
public bool CanHandle(IRequest request)
{
return request is FooRequest;
}
public IResponse HandleRequest(IRequest request)
{
return new Foo();
}
}
public class FactoryManager
{
private readonly List<IFactory> _factoryImplementations = new List<IFactory>();
public void Register(IFactory factory)
{
_factoryImplementations.Add(factory);
}
public IResponse HandleRequest(IRequest request)
{
foreach (var factory in _factoryImplementations)
{
if (factory.CanHandle(request))
{
return factory.HandleRequest(request);
}
}
return null;
}
}
class Program
{
static void Main()
{
var manager = new FactoryManager();
manager.Register(new FooFactory());
var foo = (Foo) manager.HandleRequest(new FooRequest()); // How can I remove this cast?
foo.SpecificMethod();
Console.ReadLine();
}
}
この実装の目的は、必要なときにいつでも簡単に実装を置き換えることができるようにすることです。問題は、オブジェクトにアクセスするなど、オブジェクトに固有のことをしたい場合は、要求した型を明示的にキャストする必要があることですfoo.SpecificMethod()
。
(Foo)
このキャストをなくす方法はありますか?
編集:動的変数を使用してこの問題を解決することは可能ですが、静的に型付けされた方法で解決することをお勧めします。