The purpose of this tutorial is to provide a comprehensive understanding of Behavioral Patterns in C#, with a special focus on the Observer and Strategy patterns.
At the end of this tutorial, you will be able to:
- Understand the importance of behavioral patterns in C#
- Implement the Observer and Strategy patterns
- Use these patterns to facilitate effective communication between objects
Basic knowledge of C# programming is required. Familiarity with object-oriented programming concepts will be useful.
Behavioral patterns are design patterns that identify communication patterns between objects and realize these patterns. They increase the flexibility in carrying out communication.
The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
// Define a 'Subject'
public class Subject
{
private List<Observer> _observers = new List<Observer>();
public void Attach(Observer observer)
{
_observers.Add(observer);
}
public void Notify()
{
foreach (Observer o in _observers)
{
o.Update();
}
}
}
// Define an 'Observer'
public abstract class Observer
{
public abstract void Update();
}
In this example, Subject
is an object maintaining a list of its dependents, called observers, and notifies them automatically of any state changes.
public class Context
{
private Strategy _strategy;
public Context(Strategy strategy)
{
this._strategy = strategy;
}
public void ContextInterface()
{
_strategy.AlgorithmInterface();
}
}
public abstract class Strategy
{
public abstract void AlgorithmInterface();
}
In this example, Context
is configured with a Strategy
object and maintains a reference to a Strategy object. Strategy
declares an interface common to all supported algorithms.
In this tutorial, we have learned about Behavioral Patterns in C#, focusing on the Observer and Strategy patterns. We have seen how these patterns can facilitate communication and interaction between objects.
Implement the Observer pattern where the subject is a 'WeatherStation' and the observers are 'DisplayElements' that show weather updates.
Implement the Strategy pattern where the context is a 'Duck' and the strategy is 'FlyingBehavior' with different flying behaviors for different types of ducks.