Using delegates to avoid subclassing
I woul开发者_StackOverflow中文版d like to have your opinion as to the pros and cons of using delegates instead of virtual functions aud subclassing?
I think the delegate issue is a red herring: this is really about the strategy pattern versus the template pattern.
"Favor composition over inheritance" is excellent advice, so the strategy pattern is the better default technique (whether you use objects or delegates to do your dirty work), mainly because it provides superior decoupling.
I only use subclassing (the template pattern) when there's a suitable inheritance relationship (per the Liskov Substitution Principle), the algorithm I'm varying needs access to the protected methods of the base class and I want a high degree of cohesion.
It very muych depends whether you're aiming for the object oriented or functional style really.
- Object oriented => inheritance and overriding of methods
- Functional => passing delegates to method
Usually it's best to pick one or the other, but sometimes it doesn't hurt to mix. I generally try to stick to the OO approach, since that is the main heritage of C#.
However, in certain circumstances, passing lambda epxressions to functions removes a lot of the boilerplate code. Indeed, in the extreme case, the alternative to creating a method that takes a delegate/lambda expression could be overriding the base class a dozen or so times with minor changes. Saying this, if the behaviour you want to customise is fairly fixed, than subclassing is usually the better choice.
Vague question, so you get a vague answer:
Use virtual methods and subclassing to represent a model. Use delegates to implement a mechanism.
See my answer to
When to use callbacks instead of events in c#?
for additional thoughts in this vein.
Here is my take.
- Its not object oriented programming anymore. It's the old way of doing things.
Hm. That's all I have.
精彩评论