- Download source - 20 Kb
Introduction
Software consulting companies do projects for their customers on a "Fixed Price basis" or on a "Time and Material basis". Also, the projects can be either onsite or offsite. Usually, the customers specify how they want the project to be done (Fixed price or Time and Material basis, onsite or offsite). The ultimate aim of the consulting company is to complete the project in the scheduled time, however the Strategy (or the policy) they adapt in doing the project may differ, depending on how they do the project. This is a real life example, where a Strategy Pattern is applied.
Strategy Pattern can also be used in the software design. When it is possible to have several different algorithms for performing a process, each of which is the best solution depending on the situation, then a Strategy Pattern can be used. This article is all about Strategy Pattern. It uses a programming example to explain what, when and why a Strategy Pattern is needed. Benefits and drawbacks of using Strategy Pattern in software design is discussed. Three different approaches for implementing the Pattern in C++ and known uses of Strategy Pattern are also presented in this article.
Design Patterns are meant to provide a common vocabulary for communicating design principles. Strategy Pattern is classified under Behavioral Patterns in the book, Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al. (Addison-Wesley, 1995). In this article, I will be using the terms used by 'Gang of Four (GoF)' to explain Strategy Pattern.
An Example
A progress indicator is a window that an application can use to indicate the progress of a lengthy operation (for example, an Installation Process). It is usually a rectangular window that is gradually filled, from left to right, with the highlight color as the operation progresses. It has a range and a current position. The range represents the entire duration of the operation, and the current position represents the progress the application has made towards completing the operation. The range and the current position are used to determine the percentage of the progress indicator to fill with the highlight color.
Even though left to right direction is commonly used for filling in most progress indicators, other directions like right to left, top to bottom and bottom to top can also be used for filling. I have seen some progress indicators using a bottom to top filling. Also, different types of fills like continuous fill, broken fill or pattern based fills can be used with a given filling direction.
In short, the purpose of the progress indicator remains unchanged; however, the filling direction or the filling algorithm can change. Therefore, the family of algorithms used for filling can be encapsulated in a separate filler class hierarchy and the application can configure the progress indicator with a concrete filler class. An algorithm that is encapsulated in this way is called a Strategy. So, what is a Strategy Pattern? The Strategy Pattern is a design pattern to encapsulate the variants (algorithms) and swap them strategically to alter system behavior without changing its architecture. According to GoF, Strategy Pattern is intended to, Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Strategy Pattern has three participants that include Strategy, Concrete Strategy and Context. In this example, the abstract filler class CFiller, is referred as the Strategy, the concrete filler classes CLToRFiller (for providing Left to Right fill) and CRToLFiller (for providing Right to Left fill) are referred as Concrete Strategies and the progress indicator CProgressIndicator, is referred as the Context using Strategy. The application using the progress indicator is the client for the Context. Depending on the situation, the client specifies the progress indicator (Context) with a concrete filler class object (Concrete Strategy).
CProgressIndicator maintains a reference to the CFiller object. Whenever there is a progress in the operation, the application notifies CProgressIndicator (by calling a method like SetPos); the CProgressIndicator forwards the request to the CFiller object to visually indicate the change. CFiller subclasses, CLToRFiller and CRToLFiller implement the filling algorithm (in DoFill method). By isolating the filling algorithm from the progress indicator, new filling strategies can be used without changing the progress indicator. Encapsulating the filling algorithm separately eliminates the need for multiple conditional statements to choose the right Strategy for filling. UML diagram showing the relationship between the participants of the Strategy Pattern is presented below.

Approaches for implementing Strategy Pattern in C++
Push and Pull methods can be used to provide a means of safe data exchange and reduce the coupling between the Context and Strategy objects. In the Push method, the Context pushes the data to the Strategy object and the Strategy uses the data to implement the algorithm. In this method, Context might pass some unwanted data to the Strategy object, as all Concrete Strategy objects might not require all the data. On the other hand, in the Pull method, the Context, registers itself with the Strategy which in-turn maintains a reference to the Context object and pulls the required data from it. In this method, the Context must define an elaborate set of Get methods for the Strategy objects to pull the required data. Since, the Strategy maintains a reference to the Context, both the classes are tightly coupled. The choice of Push or Pull method purely depends on the requirement.
This article discusses three different approaches for implementing the Strategy Pattern in C++. The approaches described below can use either a Push or Pull method.
- Strategy object as a required parameter to the Context
Strategy object as an optional parameter to the Context
Strategy as a template class parameter to the Context
Strategy object as a required parameter to the context
In this approach, the progress indicator (Context) takes a filler (Strategy) object as a parameter in its constructor and maintains a reference to it. The progress indicator delegates the request to the filler object when SetPos method is called. Listing 1 shows this approach. Also, Layout Manager in Java uses this approach, see Java and Strategy Pattern for explanation.
Advantage
- The progress indicator depends only on the interface of the filler class and does not interact directly with the concrete subclasses of the filler class.
- Application can select the required filler class object at run-time. SetFiller method can be used to change the filler class object after creating the progress indicator.
Disadvantage
- Application using the progress indicator must be aware of all the filler classes and must supply the progress indicator with the required filler class object.
- Progress indicator is not having any control on the scope or the lifetime of the filler class object.
Strategy object as an optional parameter to the Context
This approach is similar to the first approach, but the filler object (Strategy) is taken as an optional parameter when progress indicator (Context) is created. The progress indicator creates a default filler object (Left to Right filler), if the application did not specify the filler object during construction. Listing 2 contains C++ sample showing this approach. Demo application provided with this article uses this technique.
Advantage
- Application can specify the filler object only when it needs to change the default filler object.
- Application can select the required filler class object at run-time. SetFiller method can be used to change the filler class object after creating the progress indicator.
Disadvantage
- Progress indicator must be aware of the concrete filler class CLToRFiller, for providing the default behavior. This increases the coupling between the CProgressIndiator and CLToRFiller classes.
- Progress indicator has control only on the lifetime of the default filler object, which is CLToRFiller object in this case. But, it is not having any control on the scope or the lifetime of other filler class objects.
Strategy as a template class parameter to the Context
If there is no need to change the filler class (Strategy) at run time, it can be passed as a template parameter to the progress indicator (Context) class at compile time. Listing 3 shows this approach. Active Template Library (ATL) uses a variation of this approach to select the required
CCOMObjectxxx<>in which the Context is passed as a parameter to the Strategy class (Pull method). See ATL and Strategy Pattern for explanation.Advantage
- Progress indicator template class is instantiated only with concrete filler classes, so there is no need for the abstract CFiller class.
- Passing filler class as a template parameter provides an early binding between the progress indicator and the filler classes. This avoids runtime overhead and increases the efficiency.
- Progress indicator is responsible for the creation of the filler class object. Therefore, it has full control on the lifetime of the object.
Disadvantage
Selecting filler class at compile time provides no room for changing the object at runtime.
Benefits in using Strategy Pattern
- A family of algorithms can be defined as a class hierarchy and can be used interchangeably to alter application behavior without changing its architecture.
- By encapsulating the algorithm separately, new algorithms complying with the same interface can be easily introduced.
- The application can switch strategies at run-time.
- Strategy enables the clients to choose the required algorithm, without using a "switch" statement or a series of "if-else" statements.
- Data structures used for implementing the algorithm is completely encapsulated in Strategy classes. Therefore, the implementation of an algorithm can be changed without affecting the Context class.
- Strategy Pattern can be used instead of sub-classing the Context class. Inheritance hardwires the behavior with the Context and the behavior cannot be changed dynamically.
- The same Strategy object can be strategically shared between different Context objects. However, the shared Strategy object should not maintain states across invocations.
Drawbacks in using Strategy Pattern
- The application must be aware of all the strategies to select the right one for the right situation.
- Strategy and Context classes may be tightly coupled. The Context must supply the relevant data to the Strategy for implementing the algorithm and sometimes, all the data passed by the Context may not be relevant to all the Concrete Strategies.
- 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 behaviors, 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.
- Since, the Strategy object is created by the application in most cases; the Context has no control on lifetime of the Strategy object. However, the Context can make a local copy of the Strategy object. But, this increases the memory requirement and has a sure performance impact.
Known Uses
This section presents known uses of Strategy Pattern. Some of the known uses presented in this section are taken from the GoF book on Design Patterns.
ATL and Strategy Pattern
ATL stands for Active Template Library. It is a collection of template based classes intended to hide most of the complexities behind COM development and provide a small footprint for the component itself.
In ATL, the class of the COM object is not instantiated directly. It acts as a base class for a
CComObjectxxx<>class. For example, ifCMyClassis the COM object class, then the most derived class in the class hierarchy will be aCComObjectxxx<CMyClass>.CComObjectxxx<>provides the implementation of IUnknown methods. However, these classes not only handle the basics of reference counting, but also interact appropriately with the lock count of the module.CComObjectxxx<>classes differ slightly in their behavior and the choice of theCComObjectxxx<>depends on the aggregation, locking and destruction models. These are generic and optional features that can be applied to any COM object. For example, some COM Objects can support aggregation, some may not and some may only support aggregation. This is again true with the other two features - locking and destruction. These features can be accommodated and easily switched around without changing the functionality of the COM object.CComObject<>,CComAggObject<>,CComObjectCached<>,CComObjectNoLock<>are some ofCComObjectxxx<>classes.ATL uses the Strategy Pattern to encapsulate the behavior in different
CComObjectxxx<>classes and the COM class can select the requiredCComObjectxxx<>based on the functionality needed. Since, there is no need to change a Strategy at run-time; ATL uses C++ template for the implementation of the Strategy Pattern. ATL selects a Strategy (CComObjectxxx<>)and passes the Context (CMyClass) as a parameter to the Strategy.Java and Strategy Pattern
Strategy Pattern is also used in the implementation of the Layout Manager in Java. The Layout manager can be configured with a layout object, which can be an object of a FlowLayout, a CardLayout, a GridLayout or a GridBagLayout class. These classes encapsulate the algorithms for laying out visual components and they provide several different layouts for viewing the same visual widgets.
Other known uses
Borland's ObjectWindows uses strategies to encapsulate validation algorithms for dialog box entry fields. For example, a numeric field might have a validator to check proper range, a date field might have a validator to check the correctness of the input date and string field might have a validator for proper syntax.
ET++ uses the Strategy Pattern to encapsulate layout algorithms for text viewers.
Strategy Pattern is also used in many popular sorting algorithms, graph layout algorithms and memory allocation algorithms.
Bridge and Strategy
Often, the Strategy Pattern is confused with the Bridge Pattern. Even though, these two patterns are similar in structure, they are trying to solve two different design problems. Strategy is mainly concerned in encapsulating algorithms, whereas Bridge decouples the abstraction from the implementation, to provide different implementation for the same abstraction.
Summary
This article is all about the Strategy Pattern, it not only talked about what Strategy Pattern is, but also emphasized why and when it is needed. I have used this pattern in many of my projects including the implementation of Lexical Analyzer and Parser classes. This pattern can be applied wherever there are several different ways of performing the same task. In short, the Strategy Pattern can be used to encapsulate varying algorithms and use them to change the system behavior without altering its architecture.
Acknowledgments
Special thanks to my friend Sree Meenakshi for her helpful suggestions in improving the clarity and presentation of this article.
Listing 1 - Strategy object as a required parameter to the Context
// Forward declaration for CFiller class class CFiller; // Class declaration for CProgressIndicator class CProgressIndicator { // Method declarations public: CProgressIndicator(CFiller *); INT SetPos(INT); INT SetFiller(CFiller *); … … // Data members protected: CFiller * m_pFiller; }; // CProgressIndicator - Implementation CProgressIndicator ::CProgressIndicator(CFiller * pFiller) { // Validate pFiller ASSERT(pFiller != NULL); m_pFiller = pFiller; } INT CProgressIndicator ::SetPos(INT nPos) { // Some initialization code before forwarding the request to filler object … … // Request forwarding to filler object INT nStatus = m_pFiller->DoFill(…); … … return nStatus; } INT * CProgressIndicator ::SetFiller(CFiller * pFiller) { // Validate pFiller ASSERT(pFiller != NULL); // Set new filler object m_pFiller = pFiller; return 0; }
Listing 2 - Strategy object as an optional parameter to the Context
// Forward declaration for CFiller class class CFiller; // Class declaration for CProgressIndicator class CProgressIndicator { // Method declarations public: CProgressIndicator(CFiller * = NULL); virtual ~CProgressIndicator(); INT SetPos(INT); INT SetFiller(CFiller *); … … // Data members protected: CFiller * m_pFiller; BOOL m_bCreated; }; // CProgressIndicator - Implementation CProgressIndicator ::CProgressIndicator(CFiller * pFiller) { // Check and create filler object if(pFiller == NULL) { // Create a default Left to Right filler object m_pFiller = new CLToRFiller; m_bCreated = TRUE; } else { m_pFiller = pFiller; m_bCreated = FALSE; } } CProgressIndicator::~CProgressIndicator() { // Delete filler object, only if it is created by the progress indicator if(m_bCreated == TRUE) { delete m_pFiller; } } INT CProgressIndicator ::SetPos(INT nPos) { // Some initialization code before forwarding the request to CFiller object ASSERT(m_pFiller != NULL); … … // Request forwarding to CFiller object INT nStatus = m_pFiller->DoFill(…); … … return nStatus; } INT * CProgressIndicator ::SetFiller(CFiller * pFiller) { // Validate Filler object ASSERT(pFiller != NULL); // Delete filler object, only if it is created by the progress indicator if(m_bCreated == TRUE) { delete m_pFiller; m_bCreated = FALSE; } // Set new filler object m_pFiller = pFiller; return 0; }
Listing 3 - Strategy as a template class parameter
template <class TFiller> class CProgressIndicator { // Method declarations public: INT SetPos(INT); … … // Data members protected: TFiller m_theFiller; }; // CProgressIndicator - Implementation INT CProgressIndicator ::SetPos(INT nPos) { // Some initialization code before forwarding the request to CFiller // object … … // Request forwarding to CFiller object INT nStatus = m_theFiller.DoFill(…); … … return nStatus; } // Application code using CProgressIndicator CProgressIndicator<CLToRFiller> LtoRFillerObj;
- Strategy object as a required parameter to the Context
About T. Kulathu Sarma
Kulathu Sarma is working as a Technology Manager for GoldAvenue, a company based in Geneva, Switzerland and responsible for supporting e-business initiatives of GoldAvenue in B2B and B2C Sectors. He has been programming in C/C++ for 9 years and actively working on Patterns for the past 5 years.
相关推荐
C++ 策略模式
策略模式(Strategy Pattern)定义一系列算法,把它们一个个封装起来,并且使它们可以互相替换。Strategy 可以使算法独立于使用算法的客户端。
Design Pattern | 设计模式
Do you use design patterns? [url]http://stackoverflow.com/questions/11586/do-you-use-design-patterns[/url][quote]Any large program that is well written will use design patterns, even if they aren'...
利用Solidworks2020将挖掘机装配体转换为URDF模型
利用Solidworks2020将挖掘机装配体转换为URDF模型一、下载sw_urdf_exporter插件 URDF(Universal Robot Description Format)——通用机器人描述格式,它是ROS里边使用的一种机器人的描述文件,包含的内容有:连杆、关节,运动学和动力学参数、可视化模型、碰撞检测模型等。 一、下载sw_urdf_exporter插件 ROS提供了SolidWorks转URDF的插件(下载链接)—sw2urdfSetup.exe,下载后点击安装,安装完成后就能在sol
Applying Strategy Pattern in C++ Applications
Applying Strategy Pattern in C++ ApplicationsBy T. Kulathu Sarma When it is possible to have several different algorithms for performing a process Strategy Pattern can be used
Monocle2在R 4.3环境下的终极避坑指南:从安装到可视化全流程解析
本文提供了在R 4.3环境下安装和运行Monocle2的完整解决方案,重点解决了依赖包兼容性、源码修改及BEAM分析报错等关键问题。文章详细解析了从环境准备、依赖包处理、源码安装验证到从Seurat对象转换、拟时轨迹构建、高级可视化及性能优化的全流程,旨在帮助用户顺利完成单细胞拟时分析。
芯片设计中的复位艺术——从异步复位同步释放到复位树构建
本文深入探讨了芯片设计中复位策略的核心技术与工程实践。重点解析了异步复位同步释放这一黄金方案的原理与优势,它通过复位同步器解决了异步复位释放时的时序风险。文章进一步阐述了如何构建稳健的复位树以应对大规模SoC设计,并分析了多时钟域与低功耗场景下的复位设计挑战,为提升芯片可靠性提供了系统性的方法论。
策略模式c++版本
这是大话设计模式中的策略模式的c++版本//策略模式 #include <iostream> using namespace std;enum Cash_type { NORMALL_CASH = 0, RETURN_CASH = 1, DISCOUNT = 2, };//虚基类cashsuper class CashSuper { public: //打折函数
手把手教你如何使KeilC51与MDK共存
KeilC51与MDK共存为一个软件。
策略模式(大话设计模式)C/C++版本
商场收银软件根据客户所购买商品的单价和数量来收费。
统计信号处理基础 习题解答1-1
1-1:在雷达习题中,双程延时时间的估计量具有PDF τ0~Nτ0,στ02,其中τ0是真值。假如要估计距离请提出一种估计量R,并求它的PDF。然后,确定标准偏差στ0,使得距离估计值的99%在真值的100m以内,对电磁波传播速度取c=3×108m/s。 解答: 问题1: 由于电磁波传播速度c,信号可观察的双程传播延时τ0和双程传播距离τ0满足关系: R=cτ02 因此可采用如下估计量: R=cτ02 问题2: 由于τ0满足正态分布,且: Eτ0=τ0 varτ0=στ02 那么: E
别再让 AI 瞎写 SAP 代码了!这套 Claude Code Skill 的验证机制才是关键
本文深入解析了专为SAP CAP开发设计的AI辅助工具sap-cap-capire的技术架构。该工具采用四层设计:协议层集成MCP和LSP实现实时模型访问与语法检查;智能层通过4个专业化Agent(数据建模、服务开发等)分工协作;验证层确保代码质量;知识层存储文档模板。这种工程化设计解决了通用AI在CAP开发中面临的上下文不足、专业性缺失和代码质量保证等核心问题,通过本地化服务和实时反馈机制显著提升了开发效率。
大话设计模式C++版本-02-策略模式
概念 策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化不会影响到用算法的客户。 注意:与简单工厂模式相比,使用上只需要知道 Context 类即可, 应用场景 算法会时常变动; 用几个类封装了这些算法且有共同的父类; 一般步骤 抽象一个算法类class Strategy { public: virtual void Algorithm()=0; }; 写具体的子类class ConcreateStrategyA : public Strategy { publi
CANbus收发器TJA1051T/3/1J应用原理图设计
该收发器是为汽车工业中的高速CAN应用而设计的,为(一个带有)CAN协议控制器的微控制器)提供差分传输和接收能力。它提供了改进的电磁兼容性(EMC)和静电放电(ESD)性能,还具有:当电源电压关闭时,TJA1051T/3和TJA1051TK/3可以直接与电源电压从3V到5V的微控制器接口。这种实现能够在CAN FD快速阶段以高达5 Mbit/s的数据速率进行可靠的通信。TJA1051T/3和TJA1051TK/3上的VIO输入允许直接连接3 V至5 V微控制器(分别提供SO8和极小的HVSON8封装)
简单工厂模式和策略模式对比C++版本-大话设计模式
简单工厂模式和策略模式的区别? 简单工厂模式的实例化由工厂类来实现,用户只需要传递一个条件,由工厂生产出相应的类; 策略模式需要用户自己实例化类,传递的是实例化的对象。 简单工厂模式 //简单工厂模式 class drink { public: virtual void getResult(){} }; class caffe:public drin...
大数据学习指南从入门到精通
利用框架的力量,看懂游戏规则,才是入行的前提大多数人不懂,不会,不做,才是你的机会,你得行动,不能畏首畏尾选择才是拉差距关键,风向,比你流的汗水重要一万倍,逆风划船要累死人的为什么选择学习大数据开发,不选择Java开发?借棋弈做比喻,智商高的不要选择五子琪,要选择围棋,它能长久地吸引你。不都是在棋盘上一颗黑子一颗白子地下吗?因为围棋更复杂,能够掌握如此复杂的技艺、产生稳定输出的棋手、让我们更佩服。选择学习大数据开发也如此,能让你的职业生涯走得更远,少走弯路。
C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片
基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正
C++设计模式——策略模式(Strategy模式)
策略模式 概念 定义一系列算法,把它们一个个封装起来,并且使它们可以互相替换。Strategy 可以使算法独立于使用算法的客户端 GOF定义的UML图 例子 不使用策略模式时 假设有一个APP,是中文版的,现在业务拓展需要支持英文版、法语版、德语版等等。大部分初学者的思路应该如下 1.定义枚举类 2.大量if else 或者 switch case判断,再实现具体内容 enum Langua...
Statistics and Machine Learning Toolbox
Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具
《大话设计模式》C++实现:02 策略模式(一)商场促销实例-初始版本(switch_case)
文章目录1. 什么是策略模式?2. 策略模式的适用场景?2.1 优缺点2.1.1 好处2.1.2 当心2.2 何时使用?3. 怎样使用策略模式?3.1 方法3.2 UML类图演进3.2.1 version1 (本篇博文的demo)4. 实例4.1 结果(结论先行)4.2 具体实现5. 策略模式-相关链接 1. 什么是策略模式? 策略模式(strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。 2. 策略模式的适用场景? 2.1 优缺点 2.
SAP B1中文培訓教材_SDK
公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说
数学建模模型总结
这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!
设计模式之策略模式实例(c++)
策略模式 定义一系列算法,将每个算法封装起来,并让它们可以互相替换。策略模式可以让算法独立于使用它的客户而变化,也成为政策模式。 策略模式包含Context(环境类)、Strategy(抽象策略类)和ConcreteStrategy(具体策略类)。 策略模式实例之排序策略 由类图可知,ArrayHandler(数组处理类、环境类)聚合某些(或者依赖注入某个)具体的Sort(具体策略类)...
CppCon 2019 学习:C++ Design Patterns: From C++03 to C++17
C++ 的语言特性发展显著降低了许多设计模式的实现成本:例如,在 C++ 中构建一个配置复杂的对象: 使用方式: 如需了解 Builder 模式在现代 C++ 中如何与 、 或模板配合优化,也可以继续深入讨论。 输出示例: 特点总结: 构造过程分离:构造逻辑和类本身分开, 封装构建过程。 链式调用:Builder 的每个方法都返回引用,实现 Fluent Interface。 封装性强: 的构造函数私有,防止非法构造。 扩展灵活:可以轻松扩展更多设置项,而不影响已有逻辑。 以下是对 C++03 中 B
C++命名空间管理策略
命名空间是C++中组织代码和避免名称冲突的重要机制。合理使用命名空间可以提高代码的可维护性和可读性。命名空间的基本语法使用namespace关键字定义。C++命名空间管理策略。
【C/C++ 虚函数以及替代方案】C++ 虚函数的使用开销以及替代方案
虚函数是C++中一种特殊的成员函数,它在基类中被声明,并在派生类中被重写。虚函数的主要作用是实现多态性,即同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。 让我们用一个简单的比喻来理解这个概念。假设你是一位音乐指挥,你面前有各种各样的乐器,比如小提琴、大提琴、长笛等。你挥舞指挥棒的动作(操作)是一样的,但是不同的乐器(对象)会发出不同的声音(执行结果)。这就是多态性的一个形象的例子。
C++编程艺术从性能优化到现代设计模式的实践探索
C++语言仍在不断发展,模块化、协程等新特性正在改变编程范式。开发者需要保持学习的态度,掌握现代C++的最佳实践。性能优化与软件设计并非对立面,良好的设计往往能带来更好的性能。通过将性能意识融入开发全过程,并结合适当的设计模式,可以构建出既高效又易于维护的C++应用程序。
《C++设计模式》策略模式
介绍了C++模式的策略模式
c++ 策略模式
一、定义: 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。 1.1 角色: 抽象策略角色(Strategy): 抽象策略类。 具体策略角色(ConcreteStrategy):封装了继续相关的算法和行为。 环境角色(Context):持有一个策略类的引用,最终给客户端调用。 1.2 UML图: 二、示例 2.1 项目结构 2.2 .h .cpp文件 myStrategy.h 注:里面的具体策略角色,可以单独写成一个类文件。
设计模式C++实现——策略模式
策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。 策略模式UML图如下: 举例: 游泳池中有不同种类的鸭子,有绿头鸭,红头鸭,橡皮鸭,木头鸭等。不同鸭子的特征或行为不同。绿头鸭(MallardDuck)可以叫声是“quack”,会飞;橡皮鸭叫声是“queak”,不会飞;木头鸭不会叫,
C++主题——策略模式
C++主题——策略模式 与模板方法模式类似,策略模式也是对一些算法的调度,只不过这些算法是同类型算法,而不像模板方法模式那样是一些不同类型算法的一种顺序上的调度。模板方法像是围棋中的布局阶段,策略模式更像是接下来的实战。针对不同的事情应用不同的策略完成相同的结果,这是策略。 模板方法模式定义了一个算法的骨架,把实现交给派生类具体实现,用户不必知道怎么实现,因为他已
8777



被折叠的 条评论
为什么被折叠?



