C# Strategy Design Pattern by Delegate vs OOP

后端 未结 5 1386
悲哀的现实
悲哀的现实 2020-12-23 15:07

I wonder what\'s the pros/cons of using delegate vs OOP when implementing strategy design pattern?

Which one do you recommend to use? or what kind of problem does de

5条回答
  •  北海茫月
    2020-12-23 15:18

    In favour of delegates:

    • Delegates are easier to implement in a light-weight way using lambda expressions and dynamic methods
    • Delegates can be created from "normal" methods with the right signature
    • Delegates being multi-cast can be useful at times (though relatively rarely outside eventing)

    In favour of interfaces:

    • An object can implement an interface and still do other things: a delegate is just a delegate
    • An interface can have multiple methods; a delegate just has the one

    Could go either way:

    • With interfaces you end up with two names: the interface and the method. With delegates you just have the one. Often I find that single-method interfaces either repeat the same name twice (with variations) or the method name is very bland

    Personally I'm a big fan of delegates for their flexibility, but it really depends on the situation.

提交回复
热议问题