Design Pattern Examples
Overview of object-oriented design patterns
DesignPatternExamples_cpp Namespace Reference

The namespace containing all Design Pattern Examples implemented in C++. More...

Namespaces

namespace  LoggerHelpers
 Helper functions for all loggers.
 

Classes

class  BigResource
 Represents some big resource. In this case, a text "image" rendered as a list of strings. each entry in the list is the same width. The height of the "image" is the number of entries in the list. This image is provided by the user. More...
 
class  BigResourceManager
 Represents a manager for big resources. Also provides the class factory for the Flyweight_Class instances that are associated with a particular big resource. More...
 
class  Command
 Represents an operation that can be applied to a TextObject. This class can handle two kinds of operations, one that takes no additional parameters and one that takes two additional string parameters. More...
 
class  Command_TextObject
 Container for a string. Need to use a class that allows the text to be changed while the container (this class) remains constant. This way, operations can be applied to the text and the container's contents change but not the container (strings are immutable in C#; this dances around that problem). More...
 
class  Composite_FileAccess
 Class containing static functions for accessing a hardcoded "file" and "directory" hierarchy. More...
 
class  ConsoleLogger
 Represents a logger that writes logging to the standard output. More...
 
class  DataReaderWriter
 Represents a data reader/writer to a caller. More...
 
class  DataReaderWriterException
 Represents an error that occurred when reading or writing data in the Data reader/writer. More...
 
class  DataReaderWriterInitException
 Represents an error that occurred during initialization or shut down of the Data reader/writer. More...
 
class  Decorator
 Represents the base class of all decorators and is responsible for handling the wrapped element being decorated. More...
 
class  DeviceChain
 Represents a device chain, which is a collection of DeviceNode objects. Part of the Facade Pattern example. More...
 
struct  DeviceNode
 Represents a single device. Part of the Facade Pattern example. More...
 
class  DirEntry
 Represents a Directory entry. More...
 
struct  EntryInformation
 Represents an individual with a Name, Age, and Height. More...
 
class  Facade_ComplicatedSubSystem
 Represents some kind of system that contains multiple device chains. Part of the Facade Pattern example. More...
 
class  FileDirEntry
 Base class representing a File or Directory entry. More...
 
class  FileEntry
 Represents a File entry. More...
 
class  FileLogger
 Represents a logger that writes logging to a file. More...
 
class  Flyweight_Class
 Associates a context with a big resource. More...
 
struct  Flyweight_Context
 Represents the context for an instance of the Flyweight_Class. In this case, the context includes position and velocity. More...
 
class  Group
 Represents a single group. A group has a name and zero or more users. Users are tracked by name. More...
 
class  GroupList
 Represents a list of Groups. More...
 
class  HandlerChain
 Represents a list of handlers that all implement the IMessageHandler interface. This list can be dynamically updated and each element in the list is passed messages for processing. More...
 
struct  IDeviceNetworkHighLevel
 Represents a high level view of a complex network of device chains. A device chain can be thought of as a list of devices that can be made visible or hidden in the list but maintain the same relationship to each other regardless of visibility. More...
 
struct  IDeviceNetworkLowLevel
 Represents a network of device chains and the low level access to that network. In general, the caller should take a lock on a device chain before accessing it then release the lock when done. Part of the Facade Pattern example. More...
 
struct  IEventNotifications
 Represents a Subject that takes observers implementing the IObserverNumberChanged interface. More...
 
struct  IIterator
 Represents an iterator for some type. This is a forward-only iterator in that it can only start at 0 and increment through the items until done. More...
 
struct  ILogger
 Represents an implementation of a logger object as call from the Logger class. More...
 
struct  IMemento
 Represents a single memento, a single snapshot of the state of the Memento_TextObject class as represented by the private class Memento_TextObject.Memento. More...
 
struct  IMessageHandler
 Represents a handler in a chain of handlers. All objects that participate in the HandlerChain class must implement this interface. More...
 
class  Interpreter_Class
 Representation of a simple interpreter. More...
 
struct  INumberProducer
 Represents the Subject to the observers. This is the minimum needed by observers to get access to the data provided by the Subject class. More...
 
struct  IObserverNumberChanged
 Represents an observer to the Subject class. An observer implements this interface and then subscribes to the Subject with the interface. The observer will be called whenever a change in the number is made. More...
 
struct  IRenderElement
 Represents an element that can be rendered in text. All decorators and the core element class implement this interface. More...
 
struct  ISortEntries
 Represents a sorting strategy. More...
 
struct  IStateBehavior
 Represents a class that implements one state of the state machine. More...
 
struct  IStateContext
 Represents the context as passed to each state class. More...
 
class  ItemPair
 Represents a key/value pair where the key and value are strings. More...
 
class  Iterator
 Represents an iterator for a container by implementing the IIterator interface. More...
 
class  IteratorContainer_Class
 Represents a container that offers up two kinds of iterators for the hardcoded contents, ItemPair and std::string. More...
 
struct  IWorkByProxy
 Represents what can be done on the proxy object. This same interface is implemented on the real object as well to ensure both have the same methods. The program accesses the proxy object only through this interface. More...
 
class  Logger
 Represents the logger object to be used in the program. More...
 
class  Memento_TextObject
 Container for a string. Need to use a class that allows the text to be changed while the container (this class) remains constant. This way, operations can be applied to the text and the container's contents change but not the container (strings are immutable in C#; this dances around that problem). More...
 
struct  Message
 Represents a message sent to the windows. A message contains a type and a position. More...
 
struct  MessagePosition
 Position of the message in global coordinates (same scope of coordinates as windows). Although this can handle negative coordinates, the example is careful to use only positive coordinates. More...
 
class  MessageWindow
 Represents a rectangular region that can handle messages directed to that region. More...
 
class  MoveCommand
 Base class that represents a move command. A move command has a name and the command character that represents the command in the initial string of movement commands. More...
 
class  MoveCommandDown
 Represents the Move Down command. More...
 
class  MoveCommandLeft
 Represents the Move Left command. More...
 
class  MoveCommandNone
 Represents the Do Nothing command. This is the Null Object for this exercise. More...
 
class  MoveCommandRight
 Represents the Move Right command. More...
 
class  MoveCommandUp
 Represents the Move Up command. More...
 
class  MoveProcessor
 Represents the processor that translates the move list into a list of MoveCommand objects then either displays them or executes them. More...
 
class  NullLogger
 Represents a logger that throws away anything sent its way. More...
 
class  ObserverForBinary
 Represents an observer that prints out the current number from the Subject in binary. More...
 
class  ObserverForDecimal
 Represents an observer that prints out the current number from the Subject in decimal. More...
 
class  ObserverForHexaDecimal
 Represents an observer that prints out the current number from the Subject in hexadecimal. More...
 
class  ObserverSubject_NumberProducer
 Represents the Subject in this example, in this case, a class that contains a single number that is updated with a call to the Update() method. Whenever Update() is called, the number is incremented and all observers are notified. The observers then fetch the current number via the INumberProducer interface. More...
 
class  OrderVisitor
 A visitor used for ordering items from various shops. The user starts with an instance of this class and a list of what they want to order. More...
 
class  Program
 Contains all the top-level Design Pattern Examples to match C#. More...
 
class  Proxy_Classes_Container
 For the purposes of this example, this class hides the details about the proxy class and the real class, exposing only the IWorkByProxy interface of the proxy. In a real program, the real class would be in its own application/DLL/assembly and separate from the proxy class. More...
 
class  RedForegroundDecorator
 Represents the RedForeground decorator, which renders the wrapped content as red text. More...
 
class  StateContext_Class
 Wraps a private implementation of the state machine. The implementation maintains the context in which the state machine runs. More...
 
class  Strategy_ShowEntries_Class
 Represents a way of displaying a list of EntryInformation objects in a particular order. The order of sorting is a strategy that can be specified when the class is instantiated. The sorting strategy can be modified with a flag indicating whether the sort is reversed from normal (in this case, descending instead of ascending). More...
 
class  Strategy_SortEntries_ByAge
 Strategy for sorting the ages in ascending (or descending) order. More...
 
class  Strategy_SortEntries_ByHeight
 Strategy for sorting the heights in ascending (or descending) order. More...
 
class  Strategy_SortEntries_ByName
 Strategy for sorting the names in ascending (or descending) order. More...
 
class  Strategy_SortEntries_ClassFactory
 Holds the class constructor for the sorting strategies. More...
 
class  TextElement
 Represents the core element that can be decorated. Note that this class implements the IRenderElement but otherwise has no knowledge of any of the decorators that might be applied. More...
 
class  UnderlineDecorator
 Represents the Underline decorator, which underlines the wrapped content. More...
 
class  User
 Represents a user with a name. More...
 
class  UserGroupMediator
 Represents the mediator between caller, users, and groups. All users and groups are identified by string name. The names are case-sensitive. More...
 
class  UserGroupsContainer
 A simple container for the user and group lists. This represents some entity external to the mediator that handles such things. More...
 
class  UserList
 Represents a list of users. More...
 
class  Visitor
 All visitors must implement this base class and then override one or more of the VisitXXX() methods, depending on which shop type the visitor class is interested in. More...
 
class  Visitor_Baker
 Represent a baker shop. More...
 
class  Visitor_Butcher
 Represent a butcher shop. More...
 
class  Visitor_CondimentGrocer
 Represent a condiment grocer. More...
 
class  Visitor_Maker
 Represent a maker (of things). More...
 
class  Visitor_PickleGrocer
 Represent a pickle grocer. More...
 
class  Visitor_Restaurant
 Represent a restaurant shop. More...
 
class  Visitor_Shop
 Base class that all shops must implement. More...
 
class  Visitor_VegetableGrocer
 Represent a vegetable grocer. More...
 
class  Visitor_Village
 Represents a collection of shops that can be visited. More...
 
class  WhiteBackgroundDecorator
 Represents the WhiteBackground decorator, which changes the background color of the wrapped element to white. More...
 
class  WindowRectangle
 Represents a rectangular region, with upper left and lower right coordinates. More...
 

Typedefs

typedef std::vector< uint8_t > ByteArray
 
using two_parameter_operation = void(*)(Command_TextObject::shared_ptr_t source, std::string argument1, std::string argument2)
 Alias for a function type representing an operation applied to a TextObject using two parameters.
 
using no_parameter_operation = void(*)(Command_TextObject::shared_ptr_t source)
 Alias for a function type representing an operation applied to a TextObject that uses no additional arguments.
 
typedef std::vector< std::shared_ptr< FileDirEntry > > FileDirEntryList
 Makes it easier to refer to a list of child nodes.
 
using FlyweightClassList = std::vector< Flyweight_Class::unique_ptr_t >
 
using IntList = std::vector< int >
 Alias to make it easier to work with a vector of vectors of int.
 
typedef std::function< void()> Action
 Alias for a function pointer, using C# as inspiration for the name.
 

Enumerations

enum  FileDirTypes { File , Directory }
 Represents the type of entries allowed in the hierarchy for the Composite design pattern example. More...
 
enum  DeviceTypes {
  DEVICECONTROLLER , CORE , GTE , PCH ,
  PMC
}
 Identifies the type of devices that can appear in a device chain. Part of the Facade Pattern example. More...
 
enum  MessageType { Close = 0 , ButtonDown = 1 , ButtonUp }
 Type of message handled by MessageWindow. More...
 
enum  CurrentState {
  Initial , NormalText , DoubleQuotedText , SingleQuotedText ,
  EscapedDoubleQuoteText , EscapedSingleQuoteText , StartComment , LineComment ,
  BlockComment , EndBlockComment , Done
}
 Represents the current state of the state machine. More...
 
enum  SortOptions { ByName , ByAge , ByHeight }
 Identifies the different sorting strategies available. More...
 

Functions

void Adapter_Exercise ()
 Example of using the Adapter Pattern.
 
void Bridge_Exercise ()
 Example of using the Bridge design pattern.
 
void Command_Exercise ()
 Example of using the Command design pattern.
 
void Composite_Exercise ()
 Example of using the Composite design pattern.
 
void Decorator_Exercise ()
 Example of using the Decorator design pattern.
 
IDeviceNetworkLowLevelCreateLowLevelInstance ()
 Class factory for a singleton instance of the sub-system class. Part of the Facade Pattern example.
 
void Facade_Exercise ()
 Example of using the Facade design pattern.
 
IDeviceNetworkHighLevelCreateHighLevelInstance ()
 Class factory for a singleton instance of the IDeviceNetworkHighLevel interface. Part of the Facade Pattern example.
 
void Flyweight_Exercise ()
 Example of using the Flyweight design pattern.
 
void HandlerChain_Exercise ()
 Example of using the Handle Chain or Chain of Responsibility design pattern.
 
void Interpreter_Exercise ()
 Example of using the Interpreter design pattern.
 
void Iterator_Exercise ()
 Example of using the Iterator design pattern.
 
void Mediator_Exercise ()
 Example of using the Mediator design pattern.
 
void Memento_Exercise ()
 Example of using the Memento design pattern.
 
void NullObject_Exercise ()
 Example of using the Null Object design pattern.
 
void Observer_Exercise ()
 Example of using the Observer design pattern.
 
void Proxy_Exercise ()
 Example of using the Proxy design pattern.
 
void State_Exercise ()
 Example of using the State design pattern.
 
void Strategy_Exercise ()
 Example of using the Strategy design pattern.
 
void Visitor_Exercise ()
 Example of using the Visitor design pattern.
 

Variables

static std::unique_ptr< Facade_ComplicatedSubSystem_instance
 A singleton instance of the sub-system. Part of the Facade Pattern example.
 
const char EOF_CHAR = static_cast<char>(0xff)
 Indicates End-of-file (no more data available).
 

Detailed Description

The namespace containing all Design Pattern Examples implemented in C++.

Typedef Documentation

◆ Action

typedef std::function<void()> Action

Alias for a function pointer, using C# as inspiration for the name.

Definition at line 43 of file program.cpp.

◆ ByteArray

typedef std::vector<uint8_t> ByteArray

Definition at line 19 of file Adapter_FrontEndClass.h.

◆ FileDirEntryList

typedef std::vector<std::shared_ptr<FileDirEntry> > FileDirEntryList

Makes it easier to refer to a list of child nodes.

Definition at line 42 of file cplusplus/Composite_FileDirEntry.h.

◆ FlyweightClassList

Definition at line 177 of file Flyweight_Classes.h.

◆ IntList

using IntList = std::vector<int>

Alias to make it easier to work with a vector of vectors of int.

Definition at line 18 of file Interpreter_Class.h.

◆ no_parameter_operation

using no_parameter_operation = void (*)(Command_TextObject::shared_ptr_t source)

Alias for a function type representing an operation applied to a TextObject that uses no additional arguments.

Parameters
sourceTextObject to affect

Definition at line 91 of file Command_Classes.h.

◆ two_parameter_operation

using two_parameter_operation = void (*)(Command_TextObject::shared_ptr_t source, std::string argument1, std::string argument2)

Alias for a function type representing an operation applied to a TextObject using two parameters.

Parameters
sourceTextObject to affect
argument1First argument for the operation.
argument2Second argument for the operation.

Definition at line 84 of file Command_Classes.h.

Enumeration Type Documentation

◆ CurrentState

Represents the current state of the state machine.

Enumerator
Initial 

State before the state machine actually starts. transitions to NormalText.

NormalText 

" transitions to QuotedText, / transitions to StartComment, EOF_CHAR transitions to Done

DoubleQuotedText 

\ transitions to EscapedDoubleQuoteText, " transitions to NormalText, EOF_CHAR transitions to Done

SingleQuotedText 

‘’` transitions to EscapedSingleQuoteText, \ transitions to NormalText, EOF_CHAR transitions to Done

EscapedDoubleQuoteText 

\ transitions to QuotedText, EOF_CHAR transitions to Done

EscapedSingleQuoteText 

\ transitions to SingleQuotedText, EOF_CHAR transitions to Done

StartComment 

/ transitions to LineComment, * transitions to BlockComment, EOF_CHAR transitions to Done, all else transitions to NormalText

LineComment 

\\n transitions to NormalText, EOF_CHAR transitions to Done

BlockComment 

* transitions to EndBlockComment, EOF_CHAR transitions to Done

EndBlockComment 

/ transitions to NormalText, EOF_CHAR transitions to Done, all else transitions to BlockComment

Done 

Indicates processing is done.

Definition at line 22 of file State_Class.h.

◆ DeviceTypes

Identifies the type of devices that can appear in a device chain. Part of the Facade Pattern example.

Enumerator
DEVICECONTROLLER 

device controller. This is always visible.

CORE 

Core device.

GTE 

GTE device.

PCH 

PCH device.

PMC 

PMC device.

Definition at line 20 of file FacadeSubsystem_Interface.h.

◆ FileDirTypes

Represents the type of entries allowed in the hierarchy for the Composite design pattern example.

Enumerator
File 

Represents a file entry.

Directory 

Represents a directory entry that can contain other FileDirEntry components.

Definition at line 24 of file cplusplus/Composite_FileDirEntry.h.

◆ MessageType

Type of message handled by MessageWindow.

Enumerator
Close 

Window is asked to close itself, generally sent by the window itself in response to a button up in a Close region. Applies only to the currently selected window.

ButtonDown 

Selects a window based on position.

ButtonUp 

Take an action on the currently selected window.

Definition at line 21 of file HandlerChain_Message_Class.h.

◆ SortOptions

Identifies the different sorting strategies available.

Enumerator
ByName 

Sort alphabetically name in ascending order.

ByAge 

Sort numerically by age in ascending order.

ByHeight 

Sort numerically by height in ascending order.

Definition at line 20 of file Strategy_ISortEntries.h.

Function Documentation

◆ Adapter_Exercise()

void Adapter_Exercise ( )

Example of using the Adapter Pattern.

This example adapts functions that return error codes into a class object that throws exceptions, which is more fitting of an object- oriented language.

Definition at line 23 of file Adapter_Exercise.cpp.

References DataReaderWriter::BufferToString(), DataReaderWriter::GetMemoryBlockByteSize(), DataReaderWriter::Memory_Block_0, DataReaderWriter::Read(), DataReaderWriterInitException::what(), and DataReaderWriter::Write().

Referenced by Program::Run().

◆ Bridge_Exercise()

void Bridge_Exercise ( )

Example of using the Bridge design pattern.

The Bridge pattern is used to allow a program to offer multiple ways to perform logging without changing how the logging is used throughout the program.

In this exercise, note how the calls into the logger are the same regardless of the logger used.

Definition at line 57 of file Bridge_Exercise.cpp.

References _Bridge_Exercise_Demonstrate_Logging(), Logger::ToConsole, and Logger::ToNull.

Referenced by Program::Run().

◆ Command_Exercise()

void Command_Exercise ( )

Example of using the Command design pattern.

The Command pattern is used to encapsulate an operation or command associated with an object so that the command can be applied to the object at a later time.

In this exercise, an undo list is implemented using Commands that associate commands defined in this file with a text object. The commands are applied to the text object in succession then effectively undone.

Definition at line 145 of file Command_Exercise.cpp.

References Command_ApplyReplaceCommand(), Command_ApplyReverseCommand(), Command_Undo(), and Helpers::formatstring().

Referenced by Program::Run().

◆ Composite_Exercise()

void Composite_Exercise ( )

Example of using the Composite design pattern.

The Composite pattern is used when a collection of objects is to be formed in a hierarchical form where each object needs to be treated like any other object but some objects can contain other objects.

This example uses a file structure of file and directories to represent each object type.

Definition at line 89 of file Composite_Exercise.cpp.

References Composite_Exercise_ShowEntry(), and Composite_FileAccess::GetEntry().

Referenced by Program::Run().

◆ CreateHighLevelInstance()

IDeviceNetworkHighLevel * CreateHighLevelInstance ( )

Class factory for a singleton instance of the IDeviceNetworkHighLevel interface. Part of the Facade Pattern example.

Returns
Returns a singleton instance of the class.

Definition at line 106 of file Facade_Interface.cpp.

References _instance, and CreateLowLevelInstance().

Referenced by Facade_Exercise().

◆ CreateLowLevelInstance()

IDeviceNetworkLowLevel * CreateLowLevelInstance ( )

Class factory for a singleton instance of the sub-system class. Part of the Facade Pattern example.

Returns
Returns a singleton instance of the class.

Definition at line 396 of file Facade_ComplicatedSubSystem.cpp.

References _instance.

Referenced by CreateHighLevelInstance().

◆ Decorator_Exercise()

void Decorator_Exercise ( )

Example of using the Decorator design pattern.

The Decorator pattern is used when a class instance at run time needs to have its behavior altered. This is supported by providing wrapper classes called decorators that take instances of the IRenderElement interface. All elements look the same and can therefore recursively wrap other decorators. The base element never wraps anything and decorators must ultimately wrap a non-decorator class to be of any use.

Definition at line 30 of file Decorator_Exercise.cpp.

References Helpers::formatstring().

Referenced by Program::Run().

◆ Facade_Exercise()

void Facade_Exercise ( )

Example of using the Facade design pattern.

The Facade pattern is used when a simplified version of an interface on a complicated sub-system is needed in situations where the whole complicated sub-system does not need to be exposed.

In this example, the complicated subsystem is a representation of a device network complete with scan chains, device idcodes, and device devices that can be selected and deselected. The Facade exposed by this complex network exposes only the scan chain, getting device idcodes based on an index into those scan chains, resetting the scan chains and selecting a device to appear in the scan chain.

Definition at line 58 of file Facade_Exercise.cpp.

References _Facade_ShowIdCodes(), CreateHighLevelInstance(), IDeviceNetworkHighLevel::DisableDevicesInDeviceChain(), IDeviceNetworkHighLevel::EnableDevicesInDeviceChain(), IDeviceNetworkHighLevel::GetIdcodes(), and IDeviceNetworkHighLevel::NumChains().

Referenced by Program::Run().

◆ Flyweight_Exercise()

void Flyweight_Exercise ( )

Example of using the Flyweight design pattern.

The Flyweight pattern is used when a large object needs to be represented by a much lighter weight class, possibly multiple instances of said light-weight class.

In this example, a large object is represented by a so-called "big resource" (a two-dimensional array of text characters) containing multiple images, one associated with each flyweight class. Flyweight classes that represent offset into the big resource, along with position and velocity, are attached to the big resource image so they all share the same image but have different positions and velocities. The image is rendered to a display area through the Flyweight class. The Flyweight class instances then have their positions updated, bouncing off the edges of the display area 60 times a second. This continues for 1000 iterations or until a key is pressed.

Definition at line 306 of file Flyweight_Exercise.cpp.

References _Flyweight_ClearDisplay(), _Flyweight_GenerateBigResource(), _Flyweight_GenerateDisplay(), _Flyweight_GenerateFlyweightClasses(), _Flyweight_MoveFlyweights(), _Flyweight_RenderFlyweights(), _Flyweight_ShowDisplay(), Helpers::checkforkey(), Helpers::disableinputecho(), Helpers::enableinputecho(), Helpers::formatstring(), Helpers::getcursorposition(), Helpers::readkey(), Helpers::setcursorposition(), and Helpers::sleep().

Referenced by Program::Run().

◆ HandlerChain_Exercise()

void HandlerChain_Exercise ( )

Example of using the Handle Chain or Chain of Responsibility design pattern.

The Handler Chain pattern is used to support a dynamic list of handlers that are passed the same arguments. It is kind of the inverse of the Visitor pattern, where the Visitor pattern is a handler that is passed to all objects in a list and the Handler Chain pattern is an object passed to handlers in a list.

In this exercise, multiple rectangular regions called MessageWindows embody the handlers and the HandlerChain object passes message objects to each MessageWindow until the message is handled.

Definition at line 57 of file HandlerChain_Exercise.cpp.

References _HandlerChain_ConstructWindowChain(), ButtonDown, and ButtonUp.

Referenced by Program::Run().

◆ Interpreter_Exercise()

void Interpreter_Exercise ( )

Example of using the Interpreter design pattern.

The interpreter is instantiated then fed a series of arrays containing integer tokens. Each token represents a single word or punctuation mark. The interpreter converts that array of tokens to an actual sentence by interpreting the meaning of the tokens.

This is a very simple interpreter that handles the first token in a special way and supports punctuation. It is an example of a linear interpreter where tokens can appear in any order (it's up to the creator of the token list to make sure the outcome makes any sense).

The output shows the token list followed by the sentence produced from the tokens.

Definition at line 81 of file Interpreter_Exercise.cpp.

References _sentenceTokenLists, _TokensToString(), Helpers::formatstring(), and Interpreter_Class::Interpret().

Referenced by Program::Run().

◆ Iterator_Exercise()

void Iterator_Exercise ( )

Example of using the Iterator design pattern.

A custom container is instantiated (it already contains hard-coded data to iterate over). The custom container can then deliver three iterators, each providing a different aspect of the hard-coded data.

The output shows the output from each iterator.

Definition at line 28 of file Iterator_Exercise.cpp.

References Helpers::formatstring(), IteratorContainer_Class::GetItems(), IteratorContainer_Class::GetKeys(), IteratorContainer_Class::GetValues(), ItemPair::Key, and ItemPair::Value.

Referenced by Program::Run().

◆ Mediator_Exercise()

void Mediator_Exercise ( )

Example of using the Mediator design pattern.

A mediator is instantiated then populated with users and groups. Users are added to some of the groups.

A series of operations are then performed through the mediator. The output shows the results of each operation. Note that all operations are done using user and group names, with no knowledge of the actual lists of users and groups. The mediator hides all the details.

Definition at line 93 of file Mediator_Exercise.cpp.

References _ListToString(), UserGroupMediator::AddUserToGroup(), Helpers::formatstring(), UserGroupMediator::GetAllGroups(), UserGroupMediator::GetAllUsers(), UserGroupMediator::GetGroupsWithUser(), UserGroupMediator::GetUsersInGroup(), UserGroupMediator::IsUserInGroup(), Mediator_SetupGroups(), Mediator_SetupUsers(), UserGroupMediator::RemoveUser(), UserGroupMediator::RemoveUserFromAllGroups(), and UserGroupMediator::RemoveUserFromGroup().

Referenced by Program::Run().

◆ Memento_Exercise()

void Memento_Exercise ( )

Example of using the Memento design pattern.

In this exercise, the Memento pattern is used to take snapshots of a text object so as to form an undo list of changes to the text object. Undoing an operation means restoring a snapshot of the text object.

The undo list is implemented as a stack of memento objects that each represent a snapshot of the text object taken before each operation is applied. After all operations are applied, the mementos are used to restore the text object in reverse order, effectively undoing each operation in turn.

Compare this to the Command_Exercise() and note that the steps taken there are identical to here (except for method names, of course). The difference lies in how operations are executed and undone. Mementos make the undo process much cleaner and faster since operations do not need to be applied repeatedly to get the text object into a specific state. Specifically, compare Command_Undo() with Memento_Undo(). Also note the differences in the "Memento_ApplyXXOperation()" methods, which more cleanly separate the save from the operation.

Definition at line 155 of file Memento_Exercise.cpp.

References _mementoUndoList, Helpers::formatstring(), Memento_ApplyReplaceOperation(), Memento_ApplyReverseOperation(), Memento_Undo(), and Memento_TextObject::ToString().

Referenced by Program::Run().

◆ NullObject_Exercise()

void NullObject_Exercise ( )

Example of using the Null Object design pattern.

The Null Object pattern is where an object or function acts as a stand-in for real commands but otherwise does nothing.

In this exercise, movement commands are presented as characters in a string, with the characters 'u', 'd', 'l', and 'r' representing the moves "up", "down", "left", and "right", respectively. To keep the processing of this string simple, all other characters in the string are assigned a Null Object ("Do Nothing") version of the move command.

This example displays the commands after parsing and then "executes" commands, which consists of printing the commands out.

This example highlights the Null Object Pattern while also utilizing the Command Pattern and Interpreter Pattern.

Definition at line 38 of file NullObject_Exercise.cpp.

References MoveProcessor::ExecuteMoveList(), Helpers::formatstring(), and MoveProcessor::ShowMoveList().

Referenced by Program::Run().

◆ Observer_Exercise()

void Observer_Exercise ( )

Example of using the Observer design pattern.

The Observer pattern allows for one or more observers to react to changes in a Subject entity.

In this exercise, a number producer (the Subject) updates an internal value every time the Update() method is called. Three different observers are attached to the number producer and print out the current value in different formats whenever the number is changed.

Note: Interfaces are used throughout this example. For example, to subscribe to the number producer, the IEventNotifications interface must be obtained from the number producer. The number producer is represented to the observers with the INumberProducer interface and the observers are represented to the number producer with the IObserverNumberChanged interface. This highlights a common way to implement a "pull" style observer without having too much knowledge about the Subject.

Definition at line 38 of file Observer_Exercise.cpp.

References Helpers::formatstring(), IEventNotifications::SubscribeToNumberChanged(), and IEventNotifications::UnsubscribeFromNumberChanged().

Referenced by Program::Run().

◆ Proxy_Exercise()

void Proxy_Exercise ( )

Example of using the Proxy design pattern.

The Proxy pattern is used when a large or expensive object cannot be represented directly in the program, typically because the object is in another process or even another system altogether.

In this exercise, a Proxy class implements the same interface as the Real class, making the Proxy class look like the Real class. Calls made on the Proxy class are passed to the Real class where the work is actually done (in this case, a munged string with the text "Real class received 'xxxx'".

The only difference in output here is one additional line for the first call showing the real class being instantiated. The subsequent calls do not show this line.

Definition at line 35 of file Proxy_Exercise.cpp.

References Proxy_Classes_Container::CreateProxy(), and Helpers::formatstring().

Referenced by Program::Run().

◆ State_Exercise()

void State_Exercise ( )

Example of using the State design 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 57 of file State_Exercise.cpp.

References _State_DisplayText(), StateContext_Class::RemoveComments(), and textToFilter.

Referenced by Program::Run().

◆ Strategy_Exercise()

void Strategy_Exercise ( )

Example of using the Strategy design pattern.

The Strategy pattern provides a way to easily assign different algorithms to a class instance that can be changed at the time the class is created.

In this exercise, the Strategy_ShowEntries_Class instance sorts and displays a list of EntryInformation elements. Three different sorting strategies are provided (Name, Age, Height) and an option to reverse the normal order of the sort.

Definition at line 49 of file Strategy_Exercise.cpp.

References ByAge, ByHeight, ByName, entries, and Strategy_ShowEntries_Class::ShowEntries().

Referenced by Program::Run().

◆ Visitor_Exercise()

void Visitor_Exercise ( )

Example of using the Visitor design pattern.

The Visitor pattern is used to add functionality to a list of otherwise unchanging element objects by passing a visitor object to each element object. Each element object calls the visitor object, passing itself as an argument. The visitor object then does something based on the type of the element.

In this exercise, a collection of shop objects is initialized then an order visitor is created to retrieve an item from one of the shop objects. Along the way, shops that don't have the necessary ingredients use another order visitor to order ingredients from other shops. This approach assumes no two shops sell the same thing.

Definition at line 36 of file Visitor_Exercise.cpp.

References Helpers::formatstring().

Referenced by Program::Run().

Variable Documentation

◆ _instance

std::unique_ptr<Facade_ComplicatedSubSystem> _instance
static

A singleton instance of the sub-system. Part of the Facade Pattern example.

Definition at line 389 of file Facade_ComplicatedSubSystem.cpp.

Referenced by CreateHighLevelInstance(), and CreateLowLevelInstance().

◆ EOF_CHAR

const char EOF_CHAR = static_cast<char>(0xff)

Indicates End-of-file (no more data available).

Definition at line 47 of file State_Class.h.