Question

I've been looking at strategy pattern implementation examples and it seems to me like they are very similar to c# delegates. The only difference I see is that strategy pattern implementations don't need to explicitly declare a delegate.

But other than that, they both seem to point to functions that need a specific signature and they can both be used to determine what to execute at run time.

Is there a more obvious difference that I am missing?

I guess a related question would be, IF they are similar, what's the advantage of using one over the other?

Was it helpful?

Solution

Put simply, you can use delegates to implement strategy pattern.

Strategy pattern is a pattern. Delegates are a language feature. You use the language feature to implement the pattern. They reside in two separate categories of concepts altogether, but are related in their interaction with each other.

In other words, strategy pattern is the blueprint, the C# delegates are the bricks. You can't build the (strategy pattern) house without either. (You could build it with other kinds of bricks also, but nothing in the language feature of delegates inherently describes strategy pattern).

OTHER TIPS

Design Patterns are language agnostic, high-level solutions to commonly-encountered problems.

Delegates can be used in a platform-specific implementation of the strategy pattern for .NET, but aren't the only way of implementing such a solution.

An alternative solution is to define an interface like:

public interface IStrategy
{
    void DoStuff(...)
}

Strategies would then be represented by classes implementing this interface, rather than by a delegate.

Delegates may be an okay implementation if you expect your strategies to be very simple. For anything reasonably complex, implementing strategies as interfaces gives you a lot more options when it comes to keeping track of state, organizing things into multiple methods, sharing code between implementations, etc.

How else would you implement the strategy pattern in C#?

Patterns are a matter of architecture. Delegates are a matter of implementation.

In C#, a strategy pattern will nearly always be implemented using a delegate.

The strategy pattern is a design pattern that allows you to choose distinct functions at execution time while a delegate is a language construct that allows you to create a reference to a function and use it as a variable.

The strategy pattern is better implemented with polymorphism rather than delegates as polymorphic dispatch tends to be more elegant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top