我正在开发一个使用责任链来处理请求的应用程序。我知道如何构建链,但是如果您查看下面的示例,我将不得不调用link1.Process(request);
以启动链过程。我想弄清楚的是,有没有办法把它当作一个集合来处理,可以只调用链的第一个链接,不管它是什么?原因是,我知道基本元素是什么(最终的默认对象),但是其他程序员可以将对象添加到链中,并可能将它们放在链永远无法到达它们的位置。
public class MergedFieldProcessor
{
public MergedFieldProcessor()
{
//Define CoR here
FieldProcessor link1 = new FieldProcessor();
FieldProcessor link2 = new FieldProcessor();
FieldProcessor link3 = new FieldProcessor();
link1.SetNextProcessor(link2);
link2.SetNextProcessor(link3);
}
}
public abstract class FieldProcessor
{
private FieldProcessor NextProcessor { get; set; }
public FieldProcessor()
{
this.NextProcessor = new SprocObject();
}
public void SetNext (FieldProcessor successor)
{
this.NextProcessor = successor;
}
//determines if this link in the change is responsible for the request
public abstract Boolean WillProcess(MergedFieldProcessorRequest request);
//performs the processing required for the tag
public abstract void ProcessField(MergedFieldProcessorRequest request);
//chain method that passes the request
public void ProcessRequest(MergedFieldProcessorRequest request)
{
if (!this.WillProcess(request))
this.NextProcessor.ProcessRequest(request);
else
this.ProcessField(request);
}
}
public class MergedFieldProcessorRequest
{
public MergedField Field { get; set; }
public Dictionary<string, string> SearchParams { get; set; }
}
无法访问的链接示例:
FieldProcessor link1 = new FieldProcessor();
FieldProcessor link2 = new FieldProcessor();
FieldProcessor link3 = new FieldProcessor();
FieldProcessor link4 = new FieldProcessor();
link4.SetNext(link1);
link1.SetNext(link2);
link2.SetNext(link3);
如果他们没有修改启动进程的代码link4.Process(request)
,那么 link4 将永远不会成为链的一部分。
简而言之,是否可以动态构建链,以便如果有人将对象添加到集合中,它会自动添加到链中?