Design Pattern Examples
Overview of object-oriented design patterns
State_Exercise.c File Reference

Implementation of the State_Exercise() function as used in the State Pattern. More...

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "helpers/dynamicstring.h"
#include "helpers/split.h"
#include "helpers/strdup.h"
#include "State_RemoveComments.h"
#include "State_Exercise.h"
Include dependency graph for State_Exercise.c:

Go to the source code of this file.

Functions

static void _State_DisplayText (const char *textToDisplay)
 Helper function to display text from the State exercise. Text is displayed with line numbers.
 
void State_Exercise (void)
 Example of using the State Pattern.
 

Variables

static const char * textToFilter
 

Detailed Description

Implementation of the State_Exercise() function as used in the State Pattern.

Definition in file State_Exercise.c.

Function Documentation

◆ _State_DisplayText()

static void _State_DisplayText ( const char *  textToDisplay)
static

Helper function to display text from the State exercise. Text is displayed with line numbers.

Parameters
textToDisplayText to display.

Definition at line 27 of file State_Exercise.c.

References split(), STRDUP, SplitList::strings, and SplitList::strings_count.

Referenced by DesignPatternExamples_cpp::State_Exercise(), and State_Exercise().

◆ State_Exercise()

void State_Exercise ( void  )

Example of using the State Pattern.

The State pattern alters the behavior of the class hierarchy based on some state. This is the basis of a Finite State Machine.

In this exercise, the State class is a filter that parses text to remove C++-style line and block comments. It needs to be smart enough to ignore comment characters inside quotes.

The filtering process starts with creating the context that drives the state machine. Internal classes are provided for each state.

Definition at line 83 of file State_Exercise.c.

References _State_DisplayText(), DynamicString_Clear(), State_RemoveComments(), DynamicString::string, and textToFilter.

Variable Documentation

◆ textToFilter

const char* textToFilter
static
Initial value:
=
"/*#################### Block Comment #################################*/\n"
"//#################### Line Comment ####################################\n"
"// A comment. /* A nested comment */\n"
"\n"
"void State_Exercise() // An exercise in state machines\n"
"{\n"
" char character = '\\\"';\n"
" printf(\"\\n\");\n"
" printf(\"\\\"State\\\" /*Exercise*/\\n\");\n"
"\n"
" bool success = State_RemoveComments(textToFilter, &filteredText);\n"
"\n"
" printf(\"\\t\\tDone. //(No, really)//\\n\");\n"
"}"

Definition at line 52 of file State_Exercise.c.

Referenced by State_Exercise::Run(), DesignPatternExamples_cpp::State_Exercise(), and State_Exercise().