Consider the scalability and maintainability of delegate-based approach compared to Strategy pattern.
What are the pros and cons of delegate-based approach?
Delegate-based approach:
Pros:
Cons:
Strategy pattern vs delegate based approach
What are the pros and cons of Strategy pattern approach?
Strategy pattern:
Pros:
Cons:
Reflect on the refactoring process. How do delegates make the codebase more concise and intuitive compared to Strategy pattern?
With delegates, we can, taking the labb as en example:
Vad är en delegat?
Jag har följande kod, och vill skapa delegatinstanser och koppla dom till metoder och anropa metoderna via delegaterna.
Vad skriver jag och vart skriver jag koden?
“
// Delegatdefinition
public delegate void GreetDelegate(string name);
public class Program
{
public static void SayHello(string name)
{
Console.WriteLine($”Hej {name}!”);
}
public static void SayGoodbye(string name)
{
Console.WriteLine($"Adjö {name}!");
} "public static void Main()
{
// Skapar delegatinstanser och kopplar dem till metoder
GreetDelegate helloDel = SayHello;
GreetDelegate goodbyeDel = SayGoodbye;
// Anropar metoder via delegater
helloDel("Alice");
goodbyeDel("Bob");
}Why might one use a delegate instead of an interface in certain scenarios?
Delegates can provide a more lightweight and flexible way to represent single methods or behaviors without the need for defining separate classes or interfaces. They can make code more concise, especially when the behavior can be expressed as a simple function or as a lambda.
How do delegates offer an alternative to the Strategy pattern in design?
Instead of defining an interface and multiple implementations (as in the Strategy pattern)
Delegates allow you to encapsulate a method directly, providing a more concise way to define and pass behavior.