### Basic Proxy Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/proxy.md Demonstrates how to use the Proxy pattern. It shows client code interacting with both a RealSubject directly and through a Proxy. ```cpp int main() { std::cout << "Client: Executing the client code with a real subject:\n"; RealSubject *real_subject = new RealSubject; ClientCode(*real_subject); std::cout << "\nClient: Executing the same client code with a proxy:\n"; Proxy *proxy = new Proxy(real_subject); ClientCode(*proxy); delete real_subject; delete proxy; return 0; } ``` -------------------------------- ### Command Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/command.md Demonstrates how to use SimpleCommand and ComplexCommand with a Receiver, executing a sequence of commands. ```cpp int main() { // Simple command SimpleCommand simple("Say Hi!"); simple.Execute(); // Output: SimpleCommand: See, I can do simple things like printing (Say Hi!) // Complex command with receiver Receiver *receiver = new Receiver; std::vector commands; commands.push_back(new SimpleCommand("Say Hello!")); commands.push_back(new ComplexCommand(receiver, "Send email", "Save report")); for (const auto &cmd : commands) { cmd->Execute(); delete cmd; } delete receiver; return 0; } ``` -------------------------------- ### Basic Factory Method Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md Demonstrates direct instantiation and usage of ConcreteCreator1 and ConcreteCreator2, calling their inherited SomeOperation method. ```cpp Creator* creator = new ConcreteCreator1(); std::cout << creator->SomeOperation() << std::endl; delete creator; Creator* creator2 = new ConcreteCreator2(); std::cout << creator2->SomeOperation() << std::endl; delete creator2; ``` -------------------------------- ### Command Queue Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/command.md Demonstrates how to use a queue to store and execute a series of commands. Ensure proper memory management by deleting commands after execution. ```cpp std::queue command_queue; command_queue.push(new SimpleCommand("Task 1")); command_queue.push(new ComplexCommand(receiver, "Task 2a", "Task 2b")); while (!command_queue.empty()) { command_queue.front()->Execute(); delete command_queue.front(); command_queue.pop(); } ``` -------------------------------- ### Client Code Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/strategy.md Demonstrates how a client can use the Context class with different strategies. It shows initializing the context with a strategy and switching strategies at runtime. ```cpp void clientCode() { // Start with strategy A Context context(std::make_unique()); std::cout << "Client: Strategy is set to normal sorting.\n"; context.doSomeBusinessLogic(); std::cout << "\n"; // Switch to strategy B std::cout << "Client: Strategy is set to reverse sorting.\n"; context.set_strategy(std::make_unique()); context.doSomeBusinessLogic(); } int main() { clientCode(); return 0; } ``` -------------------------------- ### FlyweightFactory Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/flyweight.md A comprehensive example demonstrating the creation of numerous car objects using the FlyweightFactory to optimize memory by sharing common state. ```cpp FlyweightFactory factory({ SharedState("Toyota", "Camry", "Red"), SharedState("Honda", "Civic", "Blue") }); // Create cars using factory const int CARS_TO_CREATE = 100000; for (int i = 0; i < CARS_TO_CREATE; i++) { SharedState ss("Toyota", "Camry", "Red"); Flyweight flyweight = factory.GetFlyweight(ss); UniqueState unique("John Doe", "ABC-1234"); flyweight.Operation(unique); } factory.ListFlyweights(); // Show total flyweights created ``` -------------------------------- ### Adapter Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/adapter.md Demonstrates how client code interacts with Target objects and how the Adapter allows it to work with an Adaptee object through the Target interface. ```cpp int main() { // Client expects Target interface std::cout << "Client: I can work just fine with the Target objects:\n"; Target *target = new Target; std::cout << target->Request(); // Uses default implementation std::cout << "\n\n"; // Adaptee has incompatible interface Adaptee *adaptee = new Adaptee; std::cout << "Client: The Adaptee class has a weird interface.\n"; std::cout << "Adaptee: " << adaptee->SpecificRequest(); std::cout << "\n\n"; // Adapter makes Adaptee work with Target interface std::cout << "Client: But I can work with it via the Adapter:\n"; Adapter *adapter = new Adapter(adaptee); std::cout << adapter->Request(); // Uses adapted interface std::cout << "\n"; delete target; delete adaptee; delete adapter; return 0; } ``` -------------------------------- ### State Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Demonstrates how to use the Context and ConcreteState classes to observe state transitions. Initializes with ConcreteStateA and triggers requests to change states. ```cpp int main() { Context *context = new Context(new ConcreteStateA); context->Request1(); // StateA.Handle1 → transitions to StateB context->Request2(); // StateB.Handle2 → transitions to StateA delete context; return 0; } ``` -------------------------------- ### State Complex Transition Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Illustrates a state performing cleanup actions before transitioning to another state. ```cpp void Handle2() override { std::cout << "Cleaning up...\n"; this->context_->TransitionTo(new StateB); } ``` -------------------------------- ### Observer Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/observer.md Demonstrates the full lifecycle of the Observer pattern, including creating subjects and observers, notifying observers of messages, detaching observers, and cleaning up resources. This example illustrates dynamic subscription and broadcast communication. ```cpp int main() { Subject *subject = new Subject; Observer *observer1 = new Observer(*subject); Observer *observer2 = new Observer(*subject); Observer *observer3 = new Observer(*subject); // Notify all observers subject->CreateMessage("Hello World! :D"); observer3->RemoveMeFromTheList(); // Notify remaining observers subject->CreateMessage("The weather is hot today! :p"); Observer *observer4 = new Observer(*subject); subject->CreateMessage("My new car is great! ;)"); observer2->RemoveMeFromTheList(); subject->SomeBusinessLogic(); delete observer4; delete observer3; delete observer2; delete observer1; delete subject; return 0; } ``` -------------------------------- ### value() Method Example Usage Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Demonstrates how to retrieve the value stored within the singleton instance using the value() method after obtaining the instance via GetInstance. ```cpp Singleton* singleton = Singleton::GetInstance("MyValue"); std::cout << singleton->value() << "\n"; // Prints: MyValue ``` -------------------------------- ### GetInstance Example Usage Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Illustrates how to obtain the singleton instance and access its value. It shows that subsequent calls to GetInstance with different initialization values do not change the existing instance's value. ```cpp Singleton* singleton1 = Singleton::GetInstance("FOO"); Singleton* singleton2 = Singleton::GetInstance("BAR"); ``` -------------------------------- ### Singleton Basic Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Demonstrates the basic usage of the Singleton pattern, showing how GetInstance is called multiple times and returns the same instance. It verifies that subsequent calls with different values still return the original instance's value. ```cpp int main() { std::cout << "If you see the same value, singleton was reused.\n" << "If you see different values, 2 singletons were created.\n\n" << "RESULT:\n"; Singleton* s1 = Singleton::GetInstance("FOO"); Singleton* s2 = Singleton::GetInstance("BAR"); std::cout << s1->value() << "\n"; // Prints: FOO std::cout << s2->value() << "\n"; // Prints: FOO (same instance) return 0; } ``` -------------------------------- ### FlyweightFactory::GetKey() Example Usage Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/flyweight.md Shows how to generate a cache key from a SharedState object. The key is a concatenation of brand, model, and color. ```cpp SharedState ss("Toyota", "Camry", "Red"); std::string key = factory.GetKey(ss); // "Toyota_Camry_Red" ``` -------------------------------- ### FlyweightFactory::GetFlyweight() Example Usage Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/flyweight.md Demonstrates how to use the GetFlyweight method to either reuse an existing flyweight or create a new one based on the provided shared state. ```cpp FlyweightFactory factory({SharedState("Toyota", "Camry", "Red")}); SharedState ss1("Toyota", "Camry", "Red"); Flyweight fw1 = factory.GetFlyweight(ss1); // Reuses existing SharedState ss2("Honda", "Civic", "Blue"); Flyweight fw2 = factory.GetFlyweight(ss2); // Creates new ``` -------------------------------- ### Memento Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/memento.md Demonstrates the full lifecycle of the Memento pattern, including creating an originator, caretaker, performing backups, modifying state, and undoing changes. ```cpp int main() { Originator *originator = new Originator("Super-Secret-State-1"); Caretaker *caretaker = new Caretaker(originator); // Perform backup caretaker->Backup(); // Modify state originator->DoSomething(); caretaker->Backup(); originator->DoSomething(); caretaker->Backup(); originator->DoSomething(); // Show history caretaker->ShowHistory(); // Undo changes std::cout << "\nClient: Undoing...\n"; caretaker->Undo(); caretaker->Undo(); delete originator; delete caretaker; return 0; } ``` -------------------------------- ### Visitor Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/visitor.md Demonstrates how to use the Visitor pattern with ConcreteComponentA and ConcreteComponentB. The ClientCode function iterates through components and calls their Accept method with the visitor. ```cpp void ClientCode(std::array components, Visitor *visitor) { for (const Component *comp : components) { comp->Accept(visitor); } } int main() { std::array components = { new ConcreteComponentA, new ConcreteComponentB }; std::cout << "Client code works with all visitors via base interface:\n"; ConcreteVisitor1 *visitor1 = new ConcreteVisitor1; ClientCode(components, visitor1); std::cout << "\nClient code can execute different visitor logic:\n"; ConcreteVisitor2 *visitor2 = new ConcreteVisitor2; ClientCode(components, visitor2); for (const Component *comp : components) { delete comp; } delete visitor1; delete visitor2; return 0; } ``` -------------------------------- ### Abstract Factory Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/abstract-factory.md Demonstrates how to use the Abstract Factory pattern to create and use products from different variants. Client code interacts with abstract interfaces, allowing for easy switching between factory implementations. ```cpp // Create factory for variant 1 AbstractFactory *f1 = new ConcreteFactory1(); AbstractProductA *product_a = f1->CreateProductA(); AbstractProductB *product_b = f1->CreateProductB(); // Use products through abstract interface std::cout << product_b->UsefulFunctionB() << "\n"; std::cout << product_b->AnotherUsefulFunctionB(*product_a) << "\n"; // Clean up delete product_a; delete product_b; delete f1; // Create factory for variant 2 AbstractFactory *f2 = new ConcreteFactory2(); // Same client code works with variant 2 products ``` -------------------------------- ### Bridge Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/bridge.md Demonstrates how to use the Bridge pattern with different implementations and abstractions. Shows changing implementations without altering the abstraction type. ```cpp int main() { // Work with Abstraction + Implementation A ConcreteImplementationA *implementation_a = new ConcreteImplementationA; Abstraction *abstraction1 = new Abstraction(implementation_a); std::cout << abstraction1->Operation(); // Output: Abstraction: Base operation with: // ConcreteImplementationA: Here's the result on the platform A. // Change implementation without changing abstraction type ConcreteImplementationB *implementation_b = new ConcreteImplementationB; delete abstraction1->implementation_; abstraction1->implementation_ = implementation_b; std::cout << abstraction1->Operation(); // Output: Abstraction: Base operation with: // ConcreteImplementationB: Here's the result on the platform B. // Use refined abstraction with same implementations RefinedAbstraction *refined_abstraction = new RefinedAbstraction(new ConcreteImplementationA()); std::cout << refined_abstraction->Operation(); // Output: RefinedAbstraction: Refined operation with: // ConcreteImplementationA: Here's the result on the platform A. delete abstraction1; delete refined_abstraction; return 0; } ``` -------------------------------- ### State Self-Transition Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Demonstrates a state that remains in its current state after a request, without performing a transition. ```cpp void Handle1() override { std::cout << "Already in StateA\n"; // No transition } ``` -------------------------------- ### Prototype Factory Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/prototype.md Demonstrates how to use the PrototypeFactory to create and use cloned instances of different prototype types. Remember to delete the created prototype pointers after use. ```cpp PrototypeFactory *prototype_factory = new PrototypeFactory(); // Create and use a Prototype1 clone std::cout << "Let's create a Prototype 1\n"; Prototype *prototype = prototype_factory->CreatePrototype(Type::PROTOTYPE_1); prototype->Method(90); delete prototype; std::cout << "\nLet's create a Prototype 2\n"; prototype = prototype_factory->CreatePrototype(Type::PROTOTYPE_2); prototype->Method(10); delete prototype; delete prototype_factory; ``` -------------------------------- ### Basic Template Method Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/template-method.md Demonstrates how to use the Template Method pattern with concrete classes. The ClientCode function accepts an AbstractClass pointer and calls its TemplateMethod, showcasing polymorphic behavior. ```cpp void ClientCode(AbstractClass *class_) { class_->TemplateMethod(); } int main() { std::cout << "ConcreteClass1 execution:\n"; ConcreteClass1 *class1 = new ConcreteClass1; ClientCode(class1); std::cout << "\nConcreteClass2 execution:\n"; ConcreteClass2 *class2 = new ConcreteClass2; ClientCode(class2); delete class1; delete class2; return 0; } ``` -------------------------------- ### Multi-threaded Singleton Access Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Demonstrates how multiple threads can safely access the same Singleton instance. Each thread attempts to get the instance and print its value. ```cpp void ThreadFoo() { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); Singleton* singleton = Singleton::GetInstance("FOO"); std::cout << singleton->value() << "\n"; } void ThreadBar() { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); Singleton* singleton = Singleton::GetInstance("BAR"); std::cout << singleton->value() << "\n"; } int main() { std::thread t1(ThreadFoo); std::thread t2(ThreadBar); t1.join(); t2.join(); // Both threads access the same singleton instance return 0; } ``` -------------------------------- ### Mediator Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/mediator.md Demonstrates how components interact through a mediator. Components do not directly call each other; instead, they notify the mediator, which then triggers actions on other components. ```cpp int main() { Component1 *c1 = new Component1; Component2 *c2 = new Component2; ConcreteMediator *mediator = new ConcreteMediator(c1, c2); std::cout << "Client triggers operation A.\n"; c1->DoA(); // Mediator intercepts and triggers c2->DoC() std::cout << "\nClient triggers operation D.\n"; c2->DoD(); // Mediator intercepts and triggers c1->DoB() and c2->DoC() delete c1; delete c2; delete mediator; return 0; } ``` -------------------------------- ### Chain of Responsibility Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/chain-of-responsibility.md Demonstrates how to create a chain of handlers (Monkey, Squirrel, Dog) and process requests through the chain using a fluent interface for setting up the next handlers. ```cpp int main() { // Create chain: Monkey -> Squirrel -> Dog Handler *monkey = new MonkeyHandler(); Handler *squirrel = new SquirrelHandler(); Handler *dog = new DogHandler(); // Setup chain using fluent interface monkey->SetNext(squirrel)->SetNext(dog); // Test requests std::vector food = {"Nut", "Banana", "MeatBall"}; for (const auto& request : food) { std::cout << "Client: Who wants a " << request << "?\n"; std::cout << monkey->Handle(request); } delete dog; delete squirrel; delete monkey; return 0; } ``` -------------------------------- ### Composite Pattern Usage Example Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/composite.md Demonstrates how to create a tree structure using Leaf and Composite objects and how to treat them uniformly through the Component interface. Includes cleanup of dynamically allocated objects. ```cpp int main() { // Create leaves Leaf* leaf1 = new Leaf(); Leaf* leaf2 = new Leaf(); // Create composite Composite* composite1 = new Composite(); composite1->Add(leaf1); composite1->Add(leaf2); // Create another composite with the first composite as child Composite* composite2 = new Composite(); composite2->Add(composite1); Leaf* leaf3 = new Leaf(); composite2->Add(leaf3); // Uniform interface - works with both leaves and composites std::cout << "Result:\n" << composite2->Operation() << "\n"; // Cleanup delete leaf1; delete leaf2; delete leaf3; delete composite1; delete composite2; return 0; } ``` -------------------------------- ### C++ Example: Iterating Over Integers Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/iterator.md Demonstrates iterating through a Container of integers using the Iterator pattern. Elements are added to the container, and then traversed sequentially using the iterator's First(), IsDone(), and Next() methods. ```cpp Container cont; // Add elements for (int i = 0; i < 10; i++) { cont.Add(i); } // Create iterator and iterate Iterator> *it = cont.CreateIterator(); for (it->First(); !it->IsDone(); it->Next()) { std::cout << *it->Current() << std::endl; } delete it; ``` -------------------------------- ### Dynamic Observer Attach and Detach Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/observer.md Demonstrates the dynamic nature of the Observer pattern, allowing observers to attach to and detach from a subject at runtime. This example shows that detached observers are no longer notified of subject changes. ```cpp Observer *obs = new Observer(); Subject *subject = new Subject(); subject->Attach(obs); // Attach subject->Notify(); // Observer notified subject->Detach(obs); // Detach subject->Notify(); // Observer NOT notified ``` -------------------------------- ### C++ Example: Iterating Over Custom Class Objects Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/iterator.md Illustrates iterating over a Container of custom 'Data' objects using the Iterator pattern. It shows how to add instances of the 'Data' class to the container and then access their values during iteration. ```cpp Container cont; Data a(100), b(1000), c(10000); cont.Add(a); cont.Add(b); cont.Add(c); Iterator> *it = cont.CreateIterator(); for (it->First(); !it->IsDone(); it->Next()) { std::cout << it->Current()->data() << std::endl; } delete it; ``` -------------------------------- ### C++ Data Class Definition Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/iterator.md A simple class used for demonstration purposes within the Iterator pattern examples. It wraps an integer value and provides methods to set and get this value. ```cpp class Data { public: Data(int a = 0); void set_data(int a); int data(); private: int m_data_; }; ``` -------------------------------- ### Basic Facade Usage Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Demonstrates creating subsystem instances and passing them to the Facade constructor. The Facade's Operation method is then called. ```cpp int main() { Subsystem1 *subsystem1 = new Subsystem1; Subsystem2 *subsystem2 = new Subsystem2; Facade *facade = new Facade(subsystem1, subsystem2); std::cout << facade->Operation(); delete facade; // Facade destructor deletes subsystems return 0; } ``` -------------------------------- ### Direct Subsystem Access vs. Facade Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Demonstrates how clients can access subsystems directly or through a Facade. The Facade approach is generally preferred for simplicity and encapsulation. ```cpp Subsystem1 *s1 = new Subsystem1(); std::cout << s1->Operation1(); // Direct access Facade *facade = new Facade(s1, nullptr); std::cout << facade->Operation(); // Via facade ``` -------------------------------- ### Client Code Using Factory Method Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md Demonstrates how client code can work with any Creator subclass through the factory method. The client code is decoupled from the concrete product creation. ```cpp void ClientCode(const Creator& creator) { // Works regardless of which Creator subclass is used // because SomeOperation() uses the factory method creator.SomeOperation(); } // Can pass any Creator subclass ClientCode(*new ConcreteCreator1()); // Uses ConcreteProduct1 ClientCode(*new ConcreteCreator2()); // Uses ConcreteProduct2 ``` -------------------------------- ### GetInstance Method Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Provides a thread-safe way to get the single instance of the Singleton class. It uses a lock guard for synchronization and lazy initialization. ```cpp static Singleton *GetInstance(const std::string& value) { std::lock_guard lock(mutex_); if (pinstance_ == nullptr) { pinstance_ = new Singleton(value); } return pinstance_; } ``` -------------------------------- ### Builder Pattern Usage with Director Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/builder.md Demonstrates building a minimal and a full-featured product using the Director to control the construction process. Remember to manage memory for created products and builders. ```cpp Director* director = new Director(); ConcreteBuilder1* builder = new ConcreteBuilder1(); director->set_builder(builder); // Build minimal product std::cout << "Standard basic product:\n"; director->BuildMinimalViableProduct(); Product1* p = builder->GetProduct(); p->ListParts(); delete p; // Build full product std::cout << "Standard full featured product:\n"; director->BuildFullFeaturedProduct(); p = builder->GetProduct(); p->ListParts(); delete p; delete builder; delete director; ``` -------------------------------- ### Facade Self-Creation of Subsystems Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Shows how the Facade can create and manage its own subsystem instances internally when no external instances are provided. Cleanup is handled automatically. ```cpp Facade *facade = new Facade(); // Facade creates subsystems internally std::cout << facade->Operation(); delete facade; // All cleanup handled by Facade ``` -------------------------------- ### Building Chain Step-by-Step Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/chain-of-responsibility.md Build the handler chain by calling SetNext() on each handler sequentially. This approach is more verbose but clearly shows the order of handlers. ```cpp monkey->SetNext(squirrel); squirrel->SetNext(dog); ``` -------------------------------- ### Visitor Pattern Memory Management (Raw Pointers) Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/visitor.md Demonstrates manual memory management for components and visitors using raw pointers. It shows the creation, usage, and cleanup of components and a visitor. ```cpp std::array components = { new ConcreteComponentA, new ConcreteComponentB }; Visitor *visitor = new ConcreteVisitor1; // Use visitor for (const Component *comp : components) { comp->Accept(visitor); } // Cleanup for (const Component *comp : components) { delete comp; } delete visitor; ``` -------------------------------- ### Facade Class Constructor Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Initializes the Facade with optional subsystem instances or creates new ones if none are provided. The Facade takes ownership of created subsystems. ```cpp Facade( Subsystem1 *subsystem1 = nullptr, Subsystem2 *subsystem2 = nullptr) { this->subsystem1_ = subsystem1 ?: new Subsystem1; this->subsystem2_ = subsystem2 ?: new Subsystem2; } ``` -------------------------------- ### ConcreteMediator Notify Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/mediator.md Handles notifications from components and triggers appropriate actions in other components. For example, reacting to event 'A' from Component1 by calling Component2.DoC(), or reacting to event 'D' from Component2 by calling Component1.DoB() and Component2.DoC(). ```cpp void Notify(BaseComponent *sender, std::string event) const override { if (event == "A") { std::cout << "Mediator reacts on A and triggers following operations:\n"; this->component2_->DoC(); } if (event == "D") { std::cout << "Mediator reacts on D and triggers following operations:\n"; this->component1_->DoB(); this->component2_->DoC(); } } ``` -------------------------------- ### Client Provides and Facade Owns Subsystems Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Shows a memory management model where the client provides subsystems to the Facade. The Facade then takes ownership and is responsible for their cleanup upon deletion. ```cpp Subsystem1 *s1 = new Subsystem1(); Subsystem2 *s2 = new Subsystem2(); Facade *facade = new Facade(s1, s2); delete facade; // Cleans up s1 and s2 (Facade owns them) ``` -------------------------------- ### Client Code Using Target Interface Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/adapter.md Demonstrates how client code interacts with the Target interface, which can also accept an Adapter polymorphically. This highlights the pattern's benefit of decoupling. ```cpp void ClientCode(const Target *target) { std::cout << target->Request(); } int main() { Target *target = new Target(); ClientCode(target); // Works with Target Adapter *adapter = new Adapter(new Adaptee()); ClientCode(adapter); // Also works - polymorphically // Both produce Target interface output } ``` -------------------------------- ### Facade Pattern Structure in C++ Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/types.md Illustrates the Facade pattern with a simplified interface to subsystems. Includes Subsystem1, Subsystem2, and the Facade class. ```cpp class Subsystem1 { public: std::string Operation1() const; std::string OperationN() const; }; class Subsystem2 { public: std::string Operation1() const; std::string OperationZ() const; }; class Facade { protected: Subsystem1 *subsystem1_; Subsystem2 *subsystem2_; public: Facade(Subsystem1 *s1 = nullptr, Subsystem2 *s2 = nullptr); ~Facade(); std::string Operation(); }; ``` -------------------------------- ### Strategy Selection: Constructor-based Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/strategy.md Instantiate the Context with a specific strategy implementation directly in the constructor. This is useful when the strategy is known at the time of object creation. ```cpp Context context(std::make_unique()); context.doSomeBusinessLogic(); ``` -------------------------------- ### Facade Creates and Owns Subsystems Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Illustrates a memory management model where the Facade creates and owns the subsystems. Deleting the Facade automatically cleans up the owned subsystems. ```cpp Facade *facade = new Facade(); // Facade owns subsystems delete facade; // Cleans up subsystems ``` -------------------------------- ### State Stack Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Shows how to simulate nested states using a stack within the Context class. ```cpp class Context { std::stack state_stack_; void PushState(State *state) { state_stack_.push(state); } void PopState() { state_stack_.pop(); } }; ``` -------------------------------- ### Raw Pointer for Strategy (Manual Management) Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/strategy.md Demonstrates the use of raw pointers for strategy objects, highlighting the need for manual memory deallocation to avoid leaks. ```cpp Strategy *strategy = new ConcreteStrategyA(); // Manual cleanup required delete strategy; ``` -------------------------------- ### Polymorphic Client Code with Facade Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Illustrates how client code can interact with the Facade through a pointer, allowing for polymorphic behavior. The client calls the Facade's Operation method. ```cpp void ClientCode(Facade *facade) { std::cout << facade->Operation(); } int main() { Facade *facade = new Facade(); ClientCode(facade); delete facade; return 0; } ``` -------------------------------- ### Facade Operation Method Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/facade.md Orchestrates operations from both subsystems, initializing them and then ordering them to perform their actions. It returns a combined result string. ```cpp std::string Operation() { std::string result = "Facade initializes subsystems:\n"; result += this->subsystem1_->Operation1(); result += this->subsystem2_->Operation1(); result += "Facade orders subsystems to perform the action:\n"; result += this->subsystem1_->OperationN(); result += this->subsystem2_->OperationZ(); return result; } ``` -------------------------------- ### ConcreteProductB2 Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/abstract-factory.md Concrete implementation of AbstractProductB for variant 2. It can collaborate with ProductA2. ```cpp class ConcreteProductB2 : public AbstractProductB { public: std::string UsefulFunctionB() const override { return "The result of the product B2."; } std::string AnotherUsefulFunctionB(const AbstractProductA &collaborator) const override { const std::string result = collaborator.UsefulFunctionA(); return "The result of the B2 collaborating with ( " + result + " )"; } }; ``` -------------------------------- ### Command Pattern Structure in C++ Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/types.md Illustrates the Command pattern, encapsulating requests as objects. Includes Command, SimpleCommand, Receiver, and ComplexCommand. ```cpp class Command { public: virtual ~Command(); virtual void Execute() const = 0; }; class SimpleCommand : public Command { private: std::string pay_load_; public: explicit SimpleCommand(std::string pay_load); void Execute() const override; }; class Receiver { public: void DoSomething(const std::string &a); void DoSomethingElse(const std::string &b); }; class ComplexCommand : public Command { private: Receiver *receiver_; std::string a_; std::string b_; public: ComplexCommand(Receiver *receiver, std::string a, std::string b); void Execute() const override; }; ``` -------------------------------- ### Factory Method Usage Through Client Code Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md Shows how client code can work with any Creator subclass without knowing its concrete type, relying only on the Creator interface. ```cpp void ClientCode(const Creator& creator) { std::cout << "Client: I'm not aware of the creator's class, but it still works.\n" << creator.SomeOperation() << std::endl; } int main() { std::cout << "App: Launched with the ConcreteCreator1.\n"; Creator* creator = new ConcreteCreator1(); ClientCode(*creator); delete creator; std::cout << "\nApp: Launched with the ConcreteCreator2.\n"; Creator* creator2 = new ConcreteCreator2(); ClientCode(*creator2); delete creator2; return 0; } ``` -------------------------------- ### State Transition with Raw Pointers Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Manages state transitions using raw pointers, including manual cleanup of the old state. ```cpp void TransitionTo(State *state) { if (this->state_ != nullptr) delete this->state_; // Cleanup old state this->state_ = state; this->state_->set_context(this); } ``` -------------------------------- ### ConcreteProductB1 Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/abstract-factory.md Concrete implementation of AbstractProductB for variant 1. It can collaborate with ProductA1. ```cpp class ConcreteProductB1 : public AbstractProductB { public: std::string UsefulFunctionB() const override { return "The result of the product B1."; } std::string AnotherUsefulFunctionB(const AbstractProductA &collaborator) const override { const std::string result = collaborator.UsefulFunctionA(); return "The result of the B1 collaborating with ( " + result + " )"; } }; ``` -------------------------------- ### Manual Memory Management for Commands Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/command.md Demonstrates manual memory management for command objects using `new` and `delete`. Ensure that every allocated command is deleted to prevent memory leaks. ```cpp Command *cmd = new ComplexCommand(receiver, "a", "b"); cmd->Execute(); delete cmd; ``` -------------------------------- ### Building Chain with Loop Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/chain-of-responsibility.md Construct the handler chain using an array and a loop. This is useful when the handlers are already in a collection or need to be set up dynamically. ```cpp Handler *handlers[] = {monkey, squirrel, dog}; for (int i = 0; i < 2; i++) { handlers[i]->SetNext(handlers[i + 1]); } ``` -------------------------------- ### Template Method Execution Flow Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/template-method.md Illustrates the step-by-step execution of the TemplateMethod within the AbstractClass, showing which operations are called and where subclasses can intervene. ```cpp void TemplateMethod() const { this->BaseOperation1(); // Abstract: "I am doing..." this->RequiredOperations1(); // Concrete 1/2: "Implemented Operation1" this->BaseOperation2(); // Abstract: "But I let subclasses..." this->Hook1(); // Concrete 2 only: "Overridden Hook1" this->RequiredOperation2(); // Concrete 1/2: "Implemented Operation2" this->BaseOperation3(); // Abstract: "But I am doing..." this->Hook2(); // Optional: empty by default } ``` -------------------------------- ### SomeBusinessLogic() Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md A placeholder method intended for the singleton's specific business logic. It does not take any parameters and returns void. ```APIDOC ## SomeBusinessLogic() ### Description A placeholder method intended for the singleton's specific business logic. It does not take any parameters and returns void. ### Parameters None ### Return Type `void` ### Purpose Contains placeholder business logic executed by the singleton. ``` -------------------------------- ### Memory Management with Template Method Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/template-method.md Shows how client code can uniformly treat different concrete implementations of the Template Method pattern. It highlights polymorphic dispatch and proper memory deallocation. ```cpp AbstractClass *object = GetConcreteObject(); // Returns Concrete1 or Concrete2 object->TemplateMethod(); // Polymorphic dispatch delete object; ``` -------------------------------- ### Decorator Pattern Usage: Single Decorator Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/decorator.md Demonstrates how to apply a single decorator to a concrete component and observe the modified output. ```cpp Component* simple = new ConcreteComponent; std::cout << simple->Operation() << "\n"; // Output: ConcreteComponent Component* decorated = new ConcreteDecoratorA(simple); std::cout << decorated->Operation() << "\n"; // Output: ConcreteDecoratorA(ConcreteComponent) ``` -------------------------------- ### Concrete Implementation A Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/bridge.md Platform A specific implementation of the Implementation interface. It provides a concrete result for OperationImplementation. ```cpp class ConcreteImplementationA : public Implementation { public: std::string OperationImplementation() const override { return "ConcreteImplementationA: Here's the result on the platform A.\n"; } }; ``` -------------------------------- ### Adding a New Operation with Visitor Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/visitor.md Illustrates how to extend the Visitor pattern by adding a new operation. A new ConcreteVisitor3 class is defined with specific visit methods for ConcreteComponentA and ConcreteComponentB. ```cpp class ConcreteVisitor3 : public Visitor { void VisitConcreteComponentA(const ConcreteComponentA *element) const override { // New operation on ComponentA } void VisitConcreteComponentB(const ConcreteComponentB *element) const override { // New operation on ComponentB } }; ``` -------------------------------- ### Flyweight Pattern Structure in C++ Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/types.md Demonstrates the Flyweight pattern for efficient object sharing. Includes the Flyweight and FlyweightFactory classes. ```cpp class Flyweight { private: std::string shared_state_; public: Flyweight(const std::string &shared_state); void Operation(const std::string &unique_state) const; }; class FlyweightFactory { private: std::map> flyweights_; public: std::shared_ptr GetFlyweight(const std::string &shared_state); void ListFlyweights() const; }; ``` -------------------------------- ### Creator Abstract Class Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md Declares the factory method which returns an object of the Product type. Contains business logic that relies on the product. ```cpp class Creator { public: virtual ~Creator(){}; virtual Product* FactoryMethod() const = 0; std::string SomeOperation() const; }; Product* product = this->FactoryMethod(); std::string result = "Creator: The same creator's code has just worked with " + product->Operation(); delete product; return result; ``` -------------------------------- ### State Transition with Smart Pointers Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Implements state transitions using std::unique_ptr for automatic memory management. ```cpp std::unique_ptr state_; void TransitionTo(std::unique_ptr new_state) { state_ = std::move(new_state); state_->set_context(this); } ``` -------------------------------- ### Thread-Safe Singleton Initialization with Lock Guard Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Illustrates the use of `std::lock_guard` for thread-safe initialization of a Singleton instance, preventing race conditions. ```cpp std::lock_guard lock(mutex_); ``` -------------------------------- ### ConcreteComponent Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/decorator.md Provides a basic implementation of the Component interface. This is the object that will be decorated. ```cpp class ConcreteComponent : public Component { public: std::string Operation() const override { return "ConcreteComponent"; } }; ``` -------------------------------- ### State Capture and Restoration Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/memento.md Illustrates the core Memento operations for capturing the current state of an originator into a memento and restoring it later. ```cpp // Capture state Memento *snapshot = originator->Save(); // Perform modifications originator->DoSomething(); // Restore previous state originator->Restore(snapshot); ``` -------------------------------- ### Product Interface Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md Defines the interface for all concrete products. Subclasses must implement the Operation method. ```cpp class Product { public: virtual ~Product() {} virtual std::string Operation() const = 0; }; ``` -------------------------------- ### Concrete State A Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/state.md Implements state-specific behavior for ConcreteStateA. Handles request1 by transitioning the context to ConcreteStateB. ```cpp class ConcreteStateA : public State { public: void Handle1() override; void Handle2() override { std::cout << "ConcreteStateA handles request2.\n"; } }; void ConcreteStateA::Handle1() { std::cout << "ConcreteStateA handles request1.\n"; std::cout << "ConcreteStateA wants to change the state of the context.\n"; this->context_->TransitionTo(new ConcreteStateB); } ``` -------------------------------- ### ConcreteProduct1 Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md A concrete product that implements the Product interface. Returns a specific string result for its operation. ```cpp class ConcreteProduct1 : public Product { public: std::string Operation() const override { return "{Result of the ConcreteProduct1}"; } }; ``` -------------------------------- ### ConcreteProduct2 Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/factory-method.md A concrete product that implements the Product interface. Returns a different specific string result for its operation. ```cpp class ConcreteProduct2 : public Product { public: std::string Operation() const override { return "{Result of the ConcreteProduct2}"; } }; ``` -------------------------------- ### Implement Concrete Observer and Subject Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/types.md Provides concrete implementations for the Subject and Observer classes. The Subject manages a list of observers and notifies them of changes. ```cpp class Subject : public ISubject { public: void Attach(IObserver *observer) override; void Detach(IObserver *observer) override; void Notify() override; void CreateMessage(std::string message = "Empty"); void HowManyObserver(); void SomeBusinessLogic(); private: std::list list_observer_; std::string message_; }; class Observer : public IObserver { public: Observer(Subject &subject); virtual ~Observer(); void Update(const std::string &message_from_subject) override; void RemoveMeFromTheList(); void PrintInfo(); private: std::string message_from_subject_; Subject &subject_; static int static_number_; int number_; }; ``` -------------------------------- ### SimpleCommand Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/command.md A concrete command that performs a simple, self-contained action using a payload. ```cpp class SimpleCommand : public Command { private: std::string pay_load_; public: explicit SimpleCommand(std::string pay_load) : pay_load_(pay_load) {} void Execute() const override { std::cout << "SimpleCommand: See, I can do simple things like printing (" << this->pay_load_ << ")\n"; } }; ``` -------------------------------- ### Proxy Request Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/proxy.md Implements the Request method for the Proxy. It first checks access, then calls the RealSubject's Request, and finally logs the access. ```cpp void Request() const override { if (this->CheckAccess()) { this->real_subject_->Request(); this->LogAccess(); } } ``` -------------------------------- ### ConcreteVisitor2 Implementation Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/visitor.md A second concrete visitor that performs different operations on the components. It demonstrates how new operations can be added without changing component classes. ```cpp class ConcreteVisitor2 : public Visitor { public: void VisitConcreteComponentA(const ConcreteComponentA *element) const override { std::cout << element->ExclusiveMethodOfConcreteComponentA() << " + ConcreteVisitor2\n"; } void VisitConcreteComponentB(const ConcreteComponentB *element) const override { std::cout << element->SpecialMethodOfConcreteComponentB() << " + ConcreteVisitor2\n"; } }; ``` -------------------------------- ### Visitor Pattern Interfaces and Classes Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/types.md Defines the abstract Visitor interface and the abstract Component interface, along with concrete Component classes (ComponentA, ComponentB) and concrete Visitor classes (ConcreteVisitor1, ConcreteVisitor2). This forms the core structure for implementing the Visitor pattern. ```cpp class ComponentA; class ComponentB; class Visitor { public: virtual ~Visitor(); virtual void VisitConcreteComponentA(const ComponentA *element) const = 0; virtual void VisitConcreteComponentB(const ComponentB *element) const = 0; }; class Component { public: virtual ~Component(); virtual void Accept(Visitor *visitor) = 0; }; class ComponentA : public Component { public: void Accept(Visitor *visitor) override; std::string ExclusiveMethodOfConcreteComponentA() const; }; class ComponentB : public Component { public: void Accept(Visitor *visitor) override; std::string SpecialMethodOfConcreteComponentB() const; }; class ConcreteVisitor1 : public Visitor { public: void VisitConcreteComponentA(const ComponentA *element) const override; void VisitConcreteComponentB(const ComponentB *element) const override; }; class ConcreteVisitor2 : public Visitor { public: void VisitConcreteComponentA(const ComponentA *element) const override; void VisitConcreteComponentB(const ComponentB *element) const override; }; ``` -------------------------------- ### Polymorphic Client Usage of Decorator Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/decorator.md Demonstrates how client code can interact with both base components and decorated components polymorphically. The client code remains unchanged regardless of whether it receives a simple component or a decorated one. ```cpp void ClientCode(Component* component) { std::cout << "RESULT: " << component->Operation() << "\n"; } int main() { Component* simple = new ConcreteComponent; ClientCode(simple); // Works with base component Component* decorated = new ConcreteDecoratorA(simple); ClientCode(decorated); // Works with decorated component return 0; } ``` -------------------------------- ### Memory Management with Smart Pointers Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/memento.md Demonstrates a more robust approach to memory management using `std::unique_ptr` within the Caretaker, ensuring automatic cleanup of mementos. ```cpp std::vector> mementos_; // Automatic cleanup ``` -------------------------------- ### Proxy for Deferred Initialization Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/proxy.md Implements lazy initialization by creating the RealSubject instance only when the Request method is called for the first time. Useful for objects that are expensive to create and may not always be needed. ```cpp class LazyProxy : public Subject { private: mutable RealSubject *real_subject_; public: LazyProxy() : real_subject_(nullptr) {} void Request() const override { if (!real_subject_) { real_subject_ = new RealSubject(); // Create on first use } real_subject_->Request(); } }; ``` -------------------------------- ### Visitor Pattern with Composite Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/visitor.md Shows how the Visitor pattern can be used with the Composite pattern to traverse a tree structure containing both Composite and Leaf elements. ```cpp std::vector tree; tree.push_back(new Composite()); tree.push_back(new Leaf()); Visitor *visitor = new ConcreteVisitor1(); for (Component *comp : tree) { comp->Accept(visitor); // Works for both Composite and Leaf } ``` -------------------------------- ### GetInstance() Source: https://github.com/refactoringguru/design-patterns-cpp/blob/main/_autodocs/api-reference/singleton.md Provides a global point of access to the single instance of the Singleton class. It ensures thread-safe initialization using a mutex and lazy instantiation. ```APIDOC ## GetInstance() ### Description Provides a global point of access to the single instance of the Singleton class. It ensures thread-safe initialization using a mutex and lazy instantiation. ### Signature ```cpp static Singleton *Singleton::GetInstance(const std::string& value) ``` ### Parameters #### Path Parameters - **value** (const std::string&) - Required - Value for singleton initialization (used only on first call) ### Return Type `Singleton*` ### Return Value Pointer to the single instance of the Singleton class. ### Behavior 1. Acquires a lock on `mutex_` via `std::lock_guard`. 2. Checks if `pinstance_` is `nullptr` (first-time initialization). 3. If `nullptr`, creates new `Singleton` instance with provided value. 4. Returns the singleton instance. 5. Lock is released when `std::lock_guard` exits scope. ### Thread Safety Lock guard ensures thread-safe initialization across multiple threads. ### Example ```cpp Singleton* singleton1 = Singleton::GetInstance("FOO"); Singleton* singleton2 = Singleton::GetInstance("BAR"); // singleton1 and singleton2 point to the same object ``` ```