What is the need for Strategy Pattern in C#?

If your application contains a set of algorithms wherein Client should have option to choose the suitable algorithm and the algorithms must be interchangeable, then you can implement strategy pattern to encapsulate such algorithms.



Here is a code sample for it:

class contextClass {
private strategyClass stratObj;
public contextClass(strategyClass obj) {
stratObj = obj;
}
public void setContext() {
stratObj.triggerAlgorithm();
}
}
abstract class strategyClass {
public abstract void triggerAlgorithm();
}

The strategyClass can now be inherited by different classes and the context class can trigger any of these derived classes by using the following statements:
contextClass conObj = new contextClass(new derivedClass1());
conObj.setContext();

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.