Can you explain chain of responsibility(COR)?

 Posted by ArticlesMaint on 9/26/2009 | Category: Design Pattern & Practices Interview questions | Views: 3024

Chain of responsibility is used when we have series of processing which will be handled by a series of handler logic. Let’s understand what that means. There are situations when a request is handled by series of handlers. So the request is taken up by the first handler, he either can handle part of it or can not, once done he passes to the next handler down the chain. This goes on until the proper handler takes it up and completes the processing.

Figure: - Concept of Chain of Responsibility

Let’s try to understand this concept by a small sample example. Consider figure ‘Sample example’ where we have some logic to be processed. So there are three series of processes which it will go through. So process 1 does some processing and passes the same to process 2. Process 2 does some kind of processing and passed the same to process 3 to complete the processing activity.

Figure: - Sample example

Figure ‘class diagram for COR’ the three process classes which inherit from the same abstract class. One of the important points to be noted is that every process points to the next process which will be called. So in the process class we have aggregated one more process object called as ‘objProcess’. Object ‘ObjProcess’ points to next process which should be called after this process is complete.

Figure: - Class diagram for COR

Now that we have defined our classes its time to call the classes in the client. So we create all the process objects for process1 , process2 and process3. Using the ‘setProcess’ method we define the link list of process objects. You can see we have set process2 as a link list to process1 and process2 to process3. Once this link list is established we run the process which in turn runs the process according to the defined link list.

Figure: - COR client code

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response