Sobes.tech
Junior — Middle

Can you name the main design patterns in programming and architecture?

sobes.tech AI

Answer from AI

Behavioral patterns in programming and architecture help organize interactions between objects and manage execution flows. The most well-known include:

  • Observer — allows objects to subscribe to events of another object and receive notifications about changes.
  • Strategy — defines a family of algorithms, encapsulates each one, and makes them interchangeable.
  • Command — encapsulates a request as an object, allowing parameterization of clients with different requests.
  • Iterator — provides a way to access elements of a collection sequentially without exposing its internal representation.
  • State — allows an object to change its behavior when its internal state changes.

Example of the Strategy pattern in C#:

interface IStrategy {
    void Execute();
}

class ConcreteStrategyA : IStrategy {
    public void Execute() {
        Console.WriteLine("Executing Strategy A");
    }
}

class Context {
    private IStrategy _strategy;
    public Context(IStrategy strategy) {
        _strategy = strategy;
    }
    public void SetStrategy(IStrategy strategy) {
        _strategy = strategy;
    }
    public void ExecuteStrategy() {
        _strategy.Execute();
    }
}

// Usage
var context = new Context(new ConcreteStrategyA());
context.ExecuteStrategy();