Chain of Responsibility vs. Factory Pattern

  • Thread starter Thread starter Ole Hanson
  • Start date Start date
O

Ole Hanson

Hi

Wondering when to use the one over the other.
It seems that they represent the same functionality to the client, as the
Client is completely unavare of what implementation handles the client's
request.
So - what speaks for the one over the other?

/Ole
 
The Factory pattern is much like dynamic polymorphism where the base
class is an abstract class and the instantiation is done of the deriving
classes. The Factory pattern is a Creational pattern.

The Chain of responsibility pattern is much like the TCP/IP networking
where the receiver throws packets with specific headers across a domain
until the machine with the specific address catches it. This pattern
delegates responsibility and the objects are chained. Hence, when a task
needs to be implemented, the chain of resp. is traversed until an
object handles it. The Chain of responsibility pattern is a behavioral
pattern.

I hope the above can help you take a decision on which to use and when.
The following is an extract of code, in C#, for each of the patterns.


The Factory pattern
-------------------

using System;
using System.Collections;
abstract class Product
{
}
class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
abstract class Creator
{
abstract public Product FactoryMethod();
}
class ConcreteCreatorA : Creator
{
override public Product FactoryMethod()
{
return new ConcreteProductA();
} }


The Chain of responsibility pattern
-----------------------------------

using System;

abstract class Handler
{
// Fields
protected Handler successor;

// Methods
public void SetSuccessor( Handler successor )
{
this.successor = successor;
}
abstract public void HandleRequest( int request );
}

// "ConcreteHandler1"

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

// "ConcreteHandler2"

class ConcreteHandler2 : Handler
{
// Methods
override public void HandleRequest( int request )
{
if( request >= 10 && request < 20 )
Console.WriteLine("{0} handled request {1}",
this, request );
else
if( successor != null )
successor.HandleRequest( request );
}
}

// "ConcreteHandler3"

class ConcreteHandler3 : Handler
{
// Methods
override public void HandleRequest( int request )
{
if( request >= 20 && request < 30 )
Console.WriteLine("{0} handled request {1}",
this, request );
else
if( successor != null )
successor.HandleRequest( request );
}
}

// "Request"

class Request
{
// Fields
private int iRequestType;
private string strRequestParameters;

// Constructors
public Request(int requestType, string requestParameters)
{
iRequestType = requestType;
strRequestParameters = requestParameters;
}

// Properties
public int RequestType
{
get{ return iRequestType; }
set{iRequestType = value; }
}
}

/// <summary>
/// Client test
/// </summary>
public class Client
{
public static void Main( string[] args )
{
// 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 };

foreach( int request in requests )
h1.HandleRequest( request );

}
}

Code Source:dofactory.com
-------------------------

with regards,


J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com
 
Hello Ole,

Actually, the patterns are quite different. As Ravichandran pointed out,
the Factory Method pattern is creational while the Chain of Responsibility
is Behaviorial. The original "Gang of Four" book on Design Patterns divided
up the patterns into three categories, depending on the nature of their use:
Behavioral, Creational, and Structural. Each category provides a set of
patterns that are useful in different ways.

The Factory Method pattern (which is the pattern that I assume you are
referring to) defines a method that returns a base class. That method is
implemented in a an object that is responsible for creating the "correct"
child. This can be done with inheritance (as is illustrated in the code
that was uploaded) or using logic in the factory method itself, or using
polymorphism to select the correct child class based on the data types of
the parameters passed to the factory method.

Either way, once the Factory Method is done, the caller will use the child
class without knowing which child class he or she has received. This allow
seperation of the logic between the creator of a class and the user of it.

The Chain of Responsibility is quite different... it even looks fairly
different in UML. The Chain of Responsibility allows you to define a set of
child classes, each of which can handle a particular command or condition
that will show up in data. Through a little bit of creative declaration,
each child object is set up to have a reference to the next child object (in
a chain... kind of like a linked list).

The data item is passed to the head of the chain. If that class can handle
the data, it does. Otherwise, it passes the data item to the next class in
the chain. The default "end of chain" returns a null or an error.

One aspect to chain that makes it interesting is the fact that things are
handled in an order. The logic of a system can be radically changed simply
by changing the order in which a series of conditions are evaluated. The
chain of responsibility not only implements the order, but there's nothing
preventing you from creating or modifying that order at run time. In fact,
the chain is Always created at run-time. Your only real choice is: should
you create just one chain and use it over and over, or should you create a
different chain depending on conditions in your code or data?

You could use both, by having a factory method create one of a set of child
objects, and then calling a chain of responsibility where each object in the
chain specifically detects a particular child and operates on that one.
(Sounds strange, but I've got this combination in a system that I'm working
with, where the inheritance of the child objects themselves is out of my
control, and this allows me to hide the implementation of an expandible list
of commands).

Note that the Chain of Responsibility pattern is also often used in
combination with the Command pattern.

For more on how to learn about design patterns, see my blog
http://biztalkbum.blogspot.com/2004/07/how-to-learn-object-oriented.html

For more about a nice set of design patterns implemented in C#, see
http://www.dofactory.com/Patterns/Patterns.aspx

For a non-commercial design patterns site that provides links to dozens of
other sites, see
http://home.earthlink.net/~huston2/dp/patterns.html

Hope this helps,
--- Nick
 
Back
Top