我目前有一个责任链的实现,它返回实现 IResponse 的对象。
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)
演员消失?
编辑:可以使用动态变量来解决这个问题,但最好采用静态类型的方式来解决它。