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

大兔子大兔子 提交于 2019-11-30 13:48:31

Yes, you could re-write this example to use multiple if-else-cascades. But only because it's a rather simple example.

The Chain Of Responsibility is a dynamic pattern. That means that handlers can be exchanged during run-time. This is often done in UI code where several nested controls can represent the handlers. Imagine the following scenario:

You have a window. In this window there is some kind of panel. In this panel there is a text box. You right-click the text box. The executed command depends on the hierarchy. The system would ask the first handler - the textbox - to handle the click-request. If it does not know what to do with the request, it passes it on to its parent - the panel - etc. I doubt that you want to implement this kind of scenario with an if-else-cascade. Every time you change the UI, you would have to change the cascade. That's why handler objects are used. It makes the code exchangable and re-usable.

Many patterns can be implemented in a different way. This is usual practice in low-level programming languages with no object-orientation. However, these codes are usually quite inflexible and hard to maintain. Yet, this is what makes them fast.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!