4

I understand the concept of Chain of Responsibility Pattern but maybe I'm wrongly using it.

I have several types of product and I have a controller that controls the interface that is displayed for each of these types of product. The user selects the type of product and each controller is responsible for showing and interacting with the appropriate interface.

For this, I'm using the chain of responsibility pattern which doesn't sound okay I think. What I'm doing is creating a chain of controllers and, as soon as I get the product type request, I just pass it to the chain of controllers and let the appropriate controller implement the request.

But when thinking, the same could have been achieved using a simple factory but with many conditional statements.

What do you think about the use of chain of responsibility in this situation?

Noor
  • 19,638
  • 38
  • 136
  • 254
  • 1
    If it works, don't go around fixing it. I can think of the Command pattern to do the same job. – Jakub Zaverka Feb 22 '13 at 09:51
  • but the question whether chain of resposibility is application for such problem? – Noor Feb 22 '13 at 16:40
  • before i post an answer, my question is this: once a product type is chosen, is the downstream interface handling and navigation conditional on any additional variables or is it simply a function of the product type and nothing else? – amphibient Feb 22 '13 at 21:26
  • a function of the product type only, e.g. to enter the details of a specific product type, the appropriate view has to be displayed, this view is controlled by the appropriate controller, also different arguments needs to be passed to the constructor of different products, so the controller displays the appropriate interface, get the values, pass them to the proper product and returns the product – Noor Feb 23 '13 at 07:50

1 Answers1

2

As for me this task is defenitely not for chain of responsibility.
Usually in chain of responsibility the order of chain elements matters and here it is not the case.

I would try to do the following.
Create some kind of registry, which contains a map with key for productType and value for controller.

Sample implementation:

class ControllerRegistry
{
  //declaration for map and constructor

  public void Register(string productType, IProductController controller)
  {
    _map.Add(productType, controller);
  }

  public IProductController Find(string productType)
  {
    return _map[productType];
  }
}

And during application startup you should register all you controllers by calling ControllerRegistry.Register method.
You get appropriate controller by calling ControllerRegistry.Find method.
As compared with chain of responsibility you will avoid the performanse hit if number of product types is large.

EDIT
Same task topic Design pattern for handling multiple message types

Community
  • 1
  • 1
FireAlkazar
  • 1,795
  • 1
  • 14
  • 27