C# Strategy Design Pattern by Delegate vs OOP

后端 未结 5 1394
悲哀的现实
悲哀的现实 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:24

    Both techniques can be powerful and valuable - here are some of my opinions about when to use which.

    Use an Interface/Implementation approach when the strategy:

    1. maintains state
    2. needs configuration
    3. uses dependency injection
    4. needs to be configured by an IoC container (think ConnectionProvider)
    5. combines multiple responsibilities (think DataAdapter from ADO.NET)
    6. is too complex or long as a single method
    7. is likely to be subclassed to create new strategies
    8. needs to return state information to the caller
    9. needs to access internals of the object is applies to
    10. Would require too many direct parameters

    Otherwise, tend to use delegates based on Func<> or Action<>, especially if

    1. There are likely to be a very large variety of strategies (think sort expressions)
    2. The strategy is best expressed as as lambda
    3. There's an existing method you want to leverage

提交回复
热议问题