DEV Community

GabrielFMH
GabrielFMH

Posted on

BEHAVIORAL PATTERN (STATE)

BEHAVIORAL PATTERN (STATE)

Gabriel Melendez Huarachi
April 2024

Abstract
Este artículo examina la importancia y el proceso de aplicación de los patrones de comportamiento en el diseño y la implementación de sistemas de software. Los patrones de comportamiento ofrecen soluciones recurrentes a problemas comunes, permitiendo una organización eficiente, mantenible y escalable del código y las interacciones entre componentes. El artículo detalla los métodos para identificar problemas, seleccionar y diseñar patrones adecuados, así como su implementación, pruebas y ajustes. Además, se discute la importancia de la documentación para la comprensión y colaboración entre desarrolladores. También se mencionan diferentes tipos de patrones de comportamiento para ofrecer una visión general de las soluciones disponibles en este ámbito.

Abstract
This article examines the importance and process of applying behavioral patterns in the design and implementation of software systems. Behavior patterns offer recurring solutions to common problems, enabling efficient, maintainable, and scalable organization of code and interactions between components. The article details methods for identifying problems, selecting and designing suitable patterns, as well as their implementation, testing and tuning. Additionally, the importance of documentation for understanding and collaboration between developers is discussed. Different types of behavior patterns are also mentioned to provide an overview of the solutions available in this area.

Introduction
Behavioral patterns refer to recurring solutions to common problems in the design and implementation of software systems. These patterns offer a way to organize code and interactions between components in a way that is efficient, maintainable, and scalable.

Methods

Problem Identification: The first step is to identify a recurring problem in systems design for which a behavioral pattern could provide a solution.

Selecting the appropriate pattern: Select the behavior pattern that best suits your needs.

Pattern design: Once the pattern is selected, you must design how it will be integrated into your system. This involves identifying the system components that will be involved in the application of the pattern, as well as defining the interfaces and relationships between them.

Implementation: Next, you must implement the behavior pattern in your system code. This involves writing the necessary classes, methods and data structures according to the previously defined design.

Testing: It is important to perform testing to ensure that it works as expected and meets system requirements.

Refinement and adjustment: As the system evolves, you may need to refine or adjust the implementation of the behavior pattern to adapt to new requirements or changes in the system environment.

Documentation: The implementation of the behavior pattern in the system must be documented so that other developers can understand how it works and how it interacts with other components of the system.

State Pattern
State is a behavioral design that enables an object to modify its behavior in response to changes in its internal state, giving the impression that the object is changing its class type.

Structure
Context: Stores a reference to one of the specific state objects and delegates all state-specific work to this object. It communicates with the state object through the state interface and provides a method to change the current state by assigning a new state object to it.

State Interface: Declares state-specific methods that must be implemented by all specific states. Ensures that each state has relevant methods that can be invoked by the context.

Concrete States: Provide implementations for the state-specific methods defined in the State interface. They can include intermediate abstract classes to encapsulate common behaviors and avoid code duplication.

State Transition: Both context and concrete states can dynamically change the state of the context, replacing the currently bound state object. This allows the context to modify its behavior as needed, using state transitions.

Advantages and disadvantages
Advantages:
Single Responsibility Principle: Improves code structure by grouping functions related to specific states into individual classes.
Open/closed principle: Facilitates system expansion by allowing the addition of new states without altering existing state classes or the context class.
Context code simplification: Increases code clarity and maintainability by eliminating long conditional blocks from state machines.
Disadvantages:
Application Considerations: Provides a warning about possible excessive complexity when applying the pattern in situations where the state machine is simple or changes rarely.

PSEUDOCODE:

using System;

namespace RefactoringGuru.DesignPatterns.State.Conceptual
{
// The Context defines the interface of interest to clients. It also
// maintains a reference to an instance of a State subclass, which
// represents the current state of the Context.
class Context
{
// A reference to the current state of the Context.
private State _state = null;

    public Context(State state)
    {
        this.TransitionTo(state);
    }

    // The Context allows changing the State object at runtime.
    public void TransitionTo(State state)
    {
        Console.WriteLine($"Context: Transition to {state.GetType().Name}.");
        this._state = state;
        this._state.SetContext(this);
    }

    // The Context delegates part of its behavior to the current State
    // object.
    public void Request1()
    {
        this._state.Handle1();
    }

    public void Request2()
    {
        this._state.Handle2();
    }
}

// The base State class declares methods that all Concrete State should
// implement and also provides a backreference to the Context object,
// associated with the State. This backreference can be used by States to
// transition the Context to another State.
abstract class State
{
    protected Context _context;

    public void SetContext(Context context)
    {
        this._context = context;
    }

    public abstract void Handle1();

    public abstract void Handle2();
}

// Concrete States implement various behaviors, associated with a state of
// the Context.
class ConcreteStateA : State
{
    public override void Handle1()
    {
        Console.WriteLine("ConcreteStateA handles request1.");
        Console.WriteLine("ConcreteStateA wants to change the state of the context.");
        this._context.TransitionTo(new ConcreteStateB());
    }

    public override void Handle2()
    {
        Console.WriteLine("ConcreteStateA handles request2.");
    }
}

class ConcreteStateB : State
{
    public override void Handle1()
    {
        Console.Write("ConcreteStateB handles request1.");
    }

    public override void Handle2()
    {
        Console.WriteLine("ConcreteStateB handles request2.");
        Console.WriteLine("ConcreteStateB wants to change the state of the context.");
        this._context.TransitionTo(new ConcreteStateA());
    }
}

class Program
{
    static void Main(string[] args)
    {
        // The client code.
        var context = new Context(new ConcreteStateA());
        context.Request1();
        context.Request2();
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Conclusión
State pattern allows an object to change its behavior based on its internal state, providing flexibility and modularity to the system. Its structure, which includes a Context, a State Interface and Specific States, simplifies management and transition between states.

Bibliography

Patrones de diseño. (s/f). Refactoring.guru. Recuperado el 19 de abril de 2024, de https://refactoring.guru/es/design-patterns/iterator

Top comments (0)