Summer_feeds
Just another WordPress.com weblog

Chain of Responsibility

Chain Of Responsibility

Avoiding the sender of a request to its receiver, by making more than one receiver object available for the request handling.Chain the receiving objects and pass the request along the chain until the request handles this request given,

Handlers/Objects available in the pattern are:

1)Handler
2)Concrete handler
3)Client

// Chain of Responsibility pattern — Structural example
//All this will include-handler/concrete handler/client.All this three types will demostrate the pattern recognition.
using System;

namespace DoFactory.GangOfFour.Chain.Structural
{
// MainApp test application

class MainApp
{
static void Main()
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);

// Generate and process request
int[] requests = {2, 5, 14, 22, 18, 3, 27, 20};

for each (int request in requests)
{
h1.HandleRequest(request);
}

// Wait for user
Console.Read();
}
}

// “Handler”

abstract class Handler
{
protected Handler successor;

public void SetSuccessor(Handler successor)
{
this.successor = successor;
}

public abstract void HandleRequest(int request);
}

// “ConcreteHandler1”
class ConcreteHandler1 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 0 && request = 10 && request = 20 && request < 30)
{
Console.WriteLine(“{0} handled request {1}”,
this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
}

ConcreteHandler1 handled request 2
ConcreteHandler1 handled request 5
ConcreteHandler2 handled request 14
ConcreteHandler3 handled request 22
ConcreteHandler4 handled request 18
ConcreteHandler5 handled request 3
COncreteHandler6 handled request 27
ConcreteHandler7 handled request 20

No Responses to “Chain of Responsibility”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: