Strategy Method Design Pattern | C++ Design Patterns Last Updated : 05 Jan, 2024 Suggest changes Share 2 Likes Like Report Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example of the Strategy Pattern in C++: Implementation of the Strategy Pattern in C++Advantages of the Strategy Pattern in C++ Design PatternsDisadvantages of the Strategy Pattern in C++ Design PatternsExample of the Strategy Pattern in C++Problem Statement: Suppose you are working on a data processing application, and you need to implement a sorting feature that allows users to sort data in various ways. You decide to use the Strategy Pattern to handle different sorting algorithms. Implementation of the Strategy Pattern in C++Key Component of Strategy Patterns : Context: The class that contains a reference to the strategy interface and is responsible for executing the algorithm.Strategy Interface: An interface or abstract class that declares the method(s) for the algorithm. Different strategies implement this interface.Concrete Strategies: The different algorithms that implement the strategy interface.Step 1: Define the Strategy Interface C++ class SortingStrategy { public: virtual void sort(std::vector<int>& arr) = 0; }; Step 2: Implement Concrete Strategies C++ class BubbleSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Bubble Sort algorithm } }; class QuickSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Quick Sort algorithm } }; // Add more sorting algorithms as needed Step 3: Create the Context C++ class SortContext { private: SortingStrategy* strategy; public: void setStrategy(SortingStrategy* strategy) { this->strategy = strategy; } void executeStrategy(std::vector<int>& arr) { strategy->sort(arr); } }; Step 4: Utilize the Strategy Pattern C++ int main() { std::vector<int> data = {5, 2, 7, 1, 9}; SortContext context; BubbleSort bubbleSort; QuickSort quickSort; context.setStrategy(&bubbleSort); context.executeStrategy(data); // Executes Bubble Sort context.setStrategy(&quickSort); context.executeStrategy(data); // Executes Quick Sort return 0; } Overall Code for the above Example: C++ #include <bits/stdc++.h> class SortingStrategy { public: virtual void sort(std::vector<int>& arr) = 0; }; class BubbleSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Bubble Sort algorithm } }; class QuickSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Quick Sort algorithm } }; // Add more sorting algorithms as needed class SortContext { private: SortingStrategy* strategy; public: void setStrategy(SortingStrategy* strategy) { this->strategy = strategy; } void executeStrategy(std::vector<int>& arr) { strategy->sort(arr); } }; int main() { std::vector<int> data = { 5, 2, 7, 1, 9 }; SortContext context; BubbleSort bubbleSort; QuickSort quickSort; context.setStrategy(&bubbleSort); context.executeStrategy(data); // Executes Bubble Sort context.setStrategy(&quickSort); context.executeStrategy(data); // Executes Quick Sort return 0; } Diagrammatic Representation of Strategy Patterns in C++ Strategy Pattern allows the client code (in this case, the Context class) to choose between different sorting algorithms (represented by BubbleSort and QuickSort) at runtime, without modifying the client's code.This promotes flexibility because you can switch between different sorting algorithms without altering the client's implementation.It also promotes code reusability because you can add new sorting algorithms (concrete strategies) by implementing the SortingStrategy interface without modifying the existing code.The use of an abstract class or interface (SortingStrategy) ensures that all concrete strategies have a consistent interface (sort(arr) method) that can be used interchangeably by the Context class. Advantages of the Strategy Pattern in C++ Design PatternsFlexibility: Easily switch between different algorithms at runtime.Code Reusability: Strategies can be reused across different contexts.Promotes Single Responsibility: Each strategy focuses on a specific algorithm.Disadvantages of the Strategy Pattern in C++ Design PatternsMay lead to an increased number of classes, which can be overwhelming for small-scale applications.Context and the Strategy classes normally communicate through the interface specified by the abstract Strategy base class. Strategy base class must expose interface for all the required behaviours, which some concrete Strategy classes might not implement.In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one. K kotnalacooldivyansh Follow 2 Article Tags : Design Pattern Geeks Premier League System Design Geeks Premier League 2023 C++ Design Pattern +1 More Explore What is System DesignSystem Design Introduction - LLD & HLD7 min readSystem Design Life Cycle | SDLC (Design)7 min readWhat are the components of System Design?10 min readGoals and Objectives of System Design5 min readWhy is it Important to Learn System Design?6 min readImportant Key Concepts and Terminologies â Learn System Design9 min readAdvantages of System Design4 min readSystem Design FundamentalsAnalysis of Monolithic and Distributed Systems - Learn System Design10 min readRequirements Gathering in System Design6 min readDifferences between System Analysis and System Design4 min readHorizontal and Vertical Scaling | System Design5 min readCapacity Estimation in Systems Design10 min readHow to Answer a System Design Interview Problem/Question?5 min readFunctional and Non Functional Requirements5 min readWeb Server, Proxies and their role in Designing Systems9 min readScalability in System DesignWhat is Scalability and How to achieve it?7 min readWhich Scalability approach is right for our Application? - System Design4 min readPrimary Bottlenecks that Hurt the Scalability of an Application - System Design4 min readDatabases in Designing SystemsComplete Guide to Database Design - System Design11 min readSQL vs. NoSQL - Which Database to Choose in System Design?5 min readFile and Database Storage Systems in System Design4 min readBlock, Object, and File Storage in System Design6 min readDatabase Sharding - System Design8 min readDatabase Replication in System Design6 min readHigh Level Design(HLD)What is High Level Design? - Learn System Design9 min readAvailability in System Design5 min readConsistency in System Design8 min readReliability in System Design5 min readCAP Theorem in System Design5 min readWhat is API Gateway?7 min readWhat is Content Delivery Network(CDN) in System Design7 min readWhat is Load Balancer & How Load Balancing works?4 min readCaching - System Design Concept8 min readCommunication Protocols in System Design6 min readActivity Diagrams - Unified Modeling Language (UML)10 min readMessage Queues - System Design12 min readLow Level Design(LLD)What is Low Level Design or LLD?6 min readAuthentication vs Authorization in LLD - System Design3 min readPerformance Optimization Techniques for System Design3 min readObject-Oriented Analysis and Design(OOAD)6 min readData Structures and Algorithms for System Design6 min readContainerization Architecture in System Design10 min readModularity and Interfaces In System Design8 min readUnified Modeling Language (UML) Diagrams8 min readData Partitioning Techniques in System Design5 min readHow to Prepare for Low-Level Design Interviews?4 min readEssential Security Measures in System Design8 min readDesign PatternsDesign Patterns Tutorial9 min readCreational Design Patterns4 min readStructural Design Patterns7 min readBehavioral Design Patterns5 min readDesign Patterns Cheat Sheet - When to Use Which Design Pattern?7 min readInterview Guide for System DesignHow to Crack System Design Interview Round?9 min readSystem Design Interview Questions and Answers1 min read5 Common System Design Concepts for Interview Preparation12 min read5 Tips to Crack Low-Level System Design Interviews6 min readSystem Design Interview Questions & AnswersMost Commonly Asked System Design Interview Problems/Questions1 min readDesign Dropbox - A System Design Interview Question14 min readDesigning Twitter - A System Design Interview Question15+ min readSystem Design Netflix | A Complete Architecture14 min readSystem Design of Uber App | Uber System Architecture13 min readDesign BookMyShow - A System Design Interview Question10 min readDesigning Facebook Messenger | System Design Interview9 min readComplete Roadmap to Learn System Design for Beginners6 min readGuide to System Design for Freshers15+ min readHow Disney+ Hotstar Managed (5 Cr)+ Live Viewers During India's T20 World Cup Win[2024]8 min read My Profile ${profileImgHtml} My Profile Edit Profile My Courses Join Community Transactions Logout Like