Sobes.tech
Junior — Middle

Can you list the main behavioral patterns used in software system development?

sobes.tech AI

Answer from AI

Main behavioral design patterns commonly used in development:

  • Strategy — allows selecting an algorithm at runtime.
  • Observer — ensures dependent objects are notified of changes.
  • Command — encapsulates a request as an object, enabling parameterization of clients.
  • Iterator — provides a way to access elements of a collection sequentially.
  • State — allows an object to change its behavior when its internal state changes.
  • Mediator — centralizes interaction between objects.
  • Template Method — defines the skeleton of an algorithm, allowing subclasses to override specific steps.

Example of the "Strategy" pattern in Python:

class Strategy:
    def execute(self, data):
        pass

class ConcreteStrategyA(Strategy):
    def execute(self, data):
        return sorted(data)

class ConcreteStrategyB(Strategy):
    def execute(self, data):
        return sorted(data, reverse=True)

class Context:
    def __init__(self, strategy):
        self.strategy = strategy

    def do_something(self, data):
        return self.strategy.execute(data)

context = Context(ConcreteStrategyA())
print(context.do_something([3,1,2]))  # [1, 2, 3]
context.strategy = ConcreteStrategyB()
print(context.do_something([3,1,2]))  # [3, 2, 1]