Design Patterns

class Memento

Base class for implementing the Memento design pattern.

The Memento class enables derived classes to save and restore their state using Snapshot objects. It achieves this by exposing save() and load() methods that internally call the private _saveToSnapshot() and _loadFromSnapshot() methods of the derived class. These private methods are accessed using the friend mechanism, allowing Memento to interact directly with the internals of derived classes.

Usage:

Example:

class TestClass : public Memento {
    friend class Memento;

public:
    int x_ = 0;
    std::string y_;

private:
    void _saveToSnapshot(Snapshot& snapshot) const override {
        snapshot << x_ << y_;
    }

    void _loadFromSnapshot(Snapshot& snapshot) override {
        snapshot >> x_ >> y_;
    }
};

Public Types

using Snapshot = DataBuffer

Public Functions

Snapshot save()

Saves the current state of the object into a Snapshot.

This method creates a new Snapshot and invokes the _saveToSnapshot() method of the derived class to populate it with the object’s state.

Returns:

A Snapshot containing the serialized state of the object.

void load(const Snapshot &snapshot)

Restores the object’s state from a given Snapshot.

This method takes a Snapshot containing a previously saved state and invokes the _loadFromSnapshot() method of the derived class to restore the object’s state.

Parameters:

snapshot – The Snapshot containing the serialized state to restore.

Protected Functions

virtual ~Memento() = default

Virtual destructor for proper cleanup of derived classes.

Private Functions

virtual void _saveToSnapshot(Memento::Snapshot &snapshot) = 0

Saves the state of the object into a Snapshot.

Derived classes must implement this method to define how their state is serialized.

Parameters:

snapshot – The Snapshot to populate with the object’s state.

virtual void _loadFromSnapshot(Memento::Snapshot &snapshot) = 0

Restores the state of the object from a Snapshot.

Derived classes must implement this method to define how their state is deserialized.

Parameters:

snapshot – The Snapshot containing the state to restore.

template<typename TType>
class Singleton

A template class that ensures only one instance of TType exists.

The Singleton class provides a thread-safe way to create and access a single instance of a templated class TType. It guarantees that TType will be instantiated only once and provides access to that instance through a static method.

The Singleton class also prevents re-instantiation by throwing an exception if an attempt is made to instantiate the class after it has been created.

Thread Safety:

The Singleton class is designed to be thread-safe, using a mutex to ensure that the instance is only created once even in multithreaded scenarios.

Template Parameters:

TType – The class for which the singleton pattern is implemented.

Public Functions

Singleton(const Singleton&) = delete
Singleton &operator=(const Singleton&) = delete

Public Static Functions

static inline TType *instance()

Returns the managed instance of TType.

If the instance is not yet created, it throws an exception.

Protected, thread safe by using std::lock_guard.

Throws:

std::runtime_error – If the instance is not yet created.

Returns:

Pointer to the unique instance of TType.

template<typename ...TArgs>
static inline void instantiate(TArgs&&... p_args)

Instantiates the managed instance of TType with arguments.

This function will only instantiate the instance once. If an attempt is made to instantiate it after it has already been created, it throws an exception.

Template Parameters:

TArgs – The types of the arguments used to instantiate the instance.

Parameters:

p_args – The arguments for instantiating the instance.

Throws:

std::runtime_error – If the instance is already created.

Private Functions

Singleton() = default
~Singleton() = default

Private Static Attributes

static std::unique_ptr<TType> instance_ = nullptr

The unique instance of TType.

static std::mutex mutex_

Mutex to ensure thread safety.

template<typename TState>
class StateMachine

A template class for managing states and transitions.

The StateMachine class enables handling of different states and their transitions through a state machine pattern. It allows users to define actions that execute when the state machine enters a specific state, and it also allows defining transitions between states.

Template Parameters:

TState – The type of the state, typically an enum representing the states.

Public Functions

inline StateMachine()

Default constructor for StateMachine.

Note

initialized_state_ is false until any state is available.

inline void addState(const TState &state)

Adds a state to the state machine.

This method registers a state that the state machine can transition into.

Parameters:

state – The state to be added to the state machine.

inline void addTransition(const TState &startState, const TState &finalState, const std::function<void()> &lambda)

Adds a transition between two states.

This method registers a transition between a start state and a final state. It associates a lambda function to execute during the transition.

Parameters:
  • startState – The starting state of the transition.

  • finalState – The final state after the transition.

  • lambda – The lambda function to execute during the transition.

inline void addAction(const TState &state, const std::function<void()> &lambda)

Adds an action to be executed when the state machine enters a specific state.

This method registers an action to be executed when the state machine is in a specific state.

Parameters:
  • state – The state for which the action is to be registered.

  • lambda – The lambda function to execute when the state machine enters the state.

inline void transitionTo(const TState &state)

Transition the state machine to a specific state.

This method changes the state of the state machine and executes any transition action associated with it. If no transition is defined, it throws an exception.

Parameters:

state – The state to transition to.

Throws:
  • std::runtime_error – If current state has not been initialized.

  • std::invalid_argument – If the transition is not defined.

inline void update()

Updates the state machine, executing the action for the current state.

This method checks if an action is defined for the current state and executes it. If no action is defined, throws an exception.

Throws:
  • std::runtime_error – If current state has not been initialized.

  • std::invalid_argument – If the transition is not defined.

Private Members

std::unordered_set<TState> states_

Registered states in the state machine.

std::unordered_map<TState, std::function<void()>> actions_

Actions for each state (one action per state).

std::unordered_map<TState, std::unordered_map<TState, std::function<void()>>> transitions_

Transitions between states.

TState current_state

The current state of the state machine.

bool initialized_state_

Member to know if the machine has been initialized (any state is known)

template<typename TEvent, typename ...TArgs>
class Observer

A templated Observer class for subscribing to and notifying events.

This class implements the Observer design pattern. It allows users to subscribe to specific events with lambda functions, and it notifies all subscribers when an event is triggered.

Template Parameters:
  • TEvent – The type of event that will be observed.

  • TArgs – Variadic template for the types of arguments passed to the callbacks.

Public Functions

inline void subscribe(const TEvent &event, const std::function<void(TArgs...)> &lambda)

Subscribe a lambda function to an event.

This method allows a user to subscribe a lambda function to a specific event. The lambda will be called when the event is triggered via the notify method.

Parameters:
  • event – The event to subscribe to.

  • lambda – The lambda function to be called when the event is triggered.

inline void notify(const TEvent &event, TArgs... args)

Notify all subscribers of a specific event.

This method notifies all subscribers that are subscribed to the provided event. It executes all lambdas that were subscribed to the event.

Parameters:

event – The event to notify subscribers about.

Private Members

std::unordered_map<TEvent, std::vector<std::function<void(TArgs...)>>> event_map_

Map of events to lambdas.

template<typename T>
class ObservableValue

Encapsulates a value and notifies subscribers when it changes.

Template Parameters:

T – The type of the value being observed.

Public Functions

inline ObservableValue(const T &initial_value)

Constructs an ObservableValue with an initial value.

Parameters:

initial_value – The initial value.

inline const T &get() const

Gets the current value.

Returns:

The current value.

inline void set(const T &new_value)

Sets a new value and notifies subscribers if the value has changed.

Parameters:

new_value – The new value.

inline void subscribe(const std::function<void(const T&)> &callback)

Adds a subscriber to be notified of value changes.

Parameters:

callback – The callback function to be invoked when the value changes.

Private Members

T value_

The encapsulated value.

std::vector<std::function<void(const T&)>> subscribers_

List of subscribers.