Mid SOLID

How do you apply the Strategy pattern to select different caching strategies in .NET?

  • Define a caching interface:

public interface ICacheStrategy

void Cache(string key, object value);

object Retrieve(string key);

  • Implement strategies like MemoryCacheStrategy,

DistributedCacheStrategy.

  • Use DI or factory to inject the chosen strategy at runtime:

public class CacheContext

private readonly ICacheStrategy _cacheStrategy;

public CacheContext(ICacheStrategy cacheStrategy)

_cacheStrategy = cacheStrategy;

public void Cache(string key, object value) =>

_cacheStrategy.Cache(key, value);

This enables switching caching mechanisms without code changes.

More from Design Patterns in C#

All questions for this course