开发者

Implementing Chain of Responsibility with LinkedList

I'm having a hard time wrapping my head around this, and I'm hoping someone can help me.

I have a Chain of Responsibility class, and I'm wondering if I can (and would want to) implement it as a derivative of the LinkedList class. At its core, a Chain of Responsibility is, of course, a linked list, but I'm not sure if deriving from LinkedList is really appropriate here, since each implemented method needs to be able to call the same method in the successor if the current one fails.

Can you implement something like public class MyHandler : LinkedList<MyHandler>? That seems like a recursive definition, but the compiler doesn't c开发者_如何学编程onsider it a problem.

Does anyone have any insight on this?


Yes, you can inherit from LinkedList, just like you can inherit from any non-sealed class. However, I don't think it's a good idea. Inheritance is not just fo re-using methods. It conveys an "is a" relationship. Although the chain of responsibility pattern can certainly be implemented using a linked list, a chain of responsibility is not a linked list.

When deriving from the LinkedList class, you'll be exposing all its public methods. You should also ask if all those methods make sens for your class. I don't think the LinkedList.Average() makes any sens to a chain of responsibility.

You should instead store the handlers in a linked list which is a private data member of your chain of responsibility implementation.

Can you implement something like public class MyHandler : LinkedList? That seems like a recursive definition, but the compiler doesn't consider it a problem.

Yes, this is perfectly legal. It is a recursive definition and can come in handy when implementing the composite pattern, for instance. This would

I would advise against writing the class that way for the same reasons your chain of responsibility shouldn't inherit from LinkedList, but this is possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜