Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Design & Architecture » The GOF "Chain of Responsibility" Design Pattern

The GOF "Chain of Responsibility" Design Pattern

The Chain of Responsibility pattern is used to pass responsibility for handling a call to another class. This article gives a basic overview of the pattern.

Author Rank:
Total page views :  11939
Total downloads :  155
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ChainOfResponsibilitySample.zip
 
Become a Sponsor

The Chain of Responsibility pattern is used to pass responsibility for handling a call to another class. This article gives a basic overview of the pattern.

 

Part 1. Chain of Responsibility Pattern Overview

 

 

In essence, the Chain of Responsibility pattern is having a list of handlers for a command, which could be implemented as a method call or an actual GOF "Command" pattern class. When a handler receives the command, it either executes it or passes it on to the next handler in the list.

 

This could be used in many scenarios where there are multiple handlers for a command. For example, I am currently working on a project where the state of my objects are being persisted in a SQL database and, at the same time, users can choose to save some of theses objects persisted locally (with binary serialization). So when I am looking for a particular object, the lookup command first searches the shared SQL data store handler and then the command is passed to a local file serialization handler.

 

This pattern is also great for creating redundant systems for reliability. If your main database server temporarily goes offline or gets bogged down and is unable to handle requests, commands could be passed to another handler which would then cache the changes and update the database when it is back online.

 

Part 2. Framework Code.

 

For this sample, our command will be a PhoneCall class with one method "Converse()" which is our command.

 

 

class PhoneCall

{

    public PhoneCall(Person caller)

    {

        m_caller = caller;

    }

 

    private Person m_caller;

 

    public void Converse()

    {

     Console.WriteLine(string.Format("Hello. This is {0} with an important message."

     m_caller.Name));

    }
}

     

And the command handler will be a person.

 

 

 

class Person

{

    public Person(string name)

    {

        m_name = name;

    }

 

    private string m_name;

    private Person m_backupPickerUpper;

 

    public string Name

    {

        get { return m_name; }

        set { m_name = value; }

    }

 

    internal Person BackupPickerUpper

    {

        get { return m_backupPickerUpper; }

        set { m_backupPickerUpper = value; }

    }

 

    public void Pickup(PhoneCall call)

    {

        if (null != m_backupPickerUpper) // pass it on

        {

        Console.WriteLine(string.Format("{0}: Hey {1}! Pick up the phone!",

             this.m_name, m_backupPickerUpper.Name)); 

             // this is where the chain-o-responsibility is executed

             m_backupPickerUpper.Pickup(call);

        }

        else // pick it up

        {

        Console.WriteLine(string.Format("{0}: Hello?", this.m_name)); 

             // this is where it is finally handled (the call is answered)

             call.Converse();

        }

    }
}

   

The Person class has a handler method called "Pickup()" which will be used to process the incoming message (the phone call). If there is a backup handler person, the PhoneCall will be passed to the backup person, otherwise, it will be handled through calling "Converse()" on the PhoneCall object (no one seems to like picking up the phone these days... for me it is usually the video rental store telling me my rentals are past due). This is a basic implementation of the Chain of Responsibility command pattern because the call is getting passed to different handlers (people) in a chain. It will make more sense once we get to the implementing code later.

 

Part 3. Implementation Code.

 

This is how we would implement our chain of responsibility:

 

class Program

{

    static void Main(string[] args)

    {

        Person father = new Person("Father");

        Person mother = new Person("Mother");

        Person son = new Person("Son");

        Person daughter = new Person("Daughter"); 

        father.BackupPickerUpper = mother;

        mother.BackupPickerUpper = son;

        son.BackupPickerUpper = daughter; 

        Person automatedCaller = new Person("ACME Movie Rentals"); 

        PhoneCall call = new PhoneCall(automatedCaller);

        father.Pickup(call); 

        Console.ReadLine();

    }

}

 

And this would be re result:

 

Father: Hey Mother! Pick up the phone!

Mother: Hey Son! Pick up the phone!

Son: Hey Daughter! Pick up the phone!

Daughter: Hello?

Hello. This is ACME Movie Rentals with an important message.

 

Conclusion.

 

The Chain of Responsibility pattern is useful in many situations and there are many ways to implement this pattern. The route you take really depends on the problem at hand. In this sample I tried to keep it as simple as possible to avoid confusion. Hopefully this article gave you a basic understanding of how this pattern works from functional perspective.

 

Until next time,

Happy Coding


Login to add your contents and source code to this article
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ChainOfResponsibilitySample.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Another great article! by elranu On March 12, 2007
Simple and concrete Article! Thanks, Matthew!!! Ranu. www.ranu.com.ar
Reply | Email | Delete | Modify | 
Generic CoR implementation for .NET by pstach On August 26, 2008
Hi, if you need generic CoR pattern implementation for .NET you can try this: http://nchain.sourceforge.net . Cheers, P.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.