Working with Behavioral Patterns

Tutorial 4 of 5

1. Introduction

1.1 Tutorial Goal

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.

1.2 Learning Outcomes

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

1.3 Prerequisites

Basic knowledge of C# programming is required. Familiarity with object-oriented programming concepts will be useful.

2. Step-by-Step Guide

2.1 Behavioral Patterns

Behavioral patterns are design patterns that identify communication patterns between objects and realize these patterns. They increase the flexibility in carrying out communication.

2.2 Observer Pattern

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.

2.3 Strategy Pattern

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.

3. Code Examples

3.1 Observer Pattern

// 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.

3.2 Strategy Pattern

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.

4. Summary

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.

5. Practice Exercises

5.1 Exercise 1

Implement the Observer pattern where the subject is a 'WeatherStation' and the observers are 'DisplayElements' that show weather updates.

5.2 Exercise 2

Implement the Strategy pattern where the context is a 'Duck' and the strategy is 'FlyingBehavior' with different flying behaviors for different types of ducks.

Additional Resources