What is the difference between the Chain Of Responsibility design template and using a simple if-elseif-else block?

The other day, I was just looking for a chain of responsibility, and I came across this example.

Basically, there is an abstract handler, and then specific handlers, each of which implements the handle method of the parent abstract handler. The implementation is such that there is a check first to check if this handler can process the current request, and if not, it passes the request to its successor.

Now I could do the same using a simple if-else conditional block. To take the first example from the link above, here is how I changed it:

class SingleHandler { if(request > 0 && request <= 10) { // Process request } else if(request > 10 && request <= 20) { // Process request differently } else if(request > 20 && request <= 30) { // Process request differently } } 

Now, my question is: what is the fundamental difference between the two? Is there any specific reason I should use Chain Of Responsibility at all if I can provide the same functionality using if-else blocks? Which one is better in terms of performance, memory consumption, maintainability, scalability?

+6
source share
1 answer

Yes, you can rewrite this example to use multiple if-else cascades. But just because it is a fairly simple example.

The chain of responsibility is a dynamic model. This means that handlers can be exchanged at runtime. This is often done in interface code, where several nested controls can represent handlers. Imagine the following scenario:

You have a window. There is some kind of panel in this window. This panel has a text box. You right-click the text box. The executed command depends on the hierarchy. The system will ask the first handler - a text field - to process a click request. If he does not know what to do with the request, he passes it to his parent - the panel - etc. I doubt that you want to implement such a scenario with an if-else cascade. Each time you change the user interface, you will have to change the cascade. This is why handler objects are used. This makes the code interchangeable and reusable.

Many templates can be implemented differently. This is common practice in low-level programming languages ​​without object orientation. However, these codes are usually quite inflexible and difficult to withstand. However, this is what makes them fast.

+14
source

Source: https://habr.com/ru/post/969688/


All Articles