C++中的策略模式:灵活多变的设计模式

C/C++ 专栏收录该内容
¥99.90 ¥299.90
170篇文章

C++中的策略模式:灵活多变的设计模式

策略模式是一种经典的设计模式,它可以让程序具有更好的灵活性、可扩展性、可维护性。在C++中,通过对象的多态性,我们可以轻松地实现策略模式。

首先,我们需要定义一个抽象基类,用来声明策略模式的接口。在这个基类中,我们定义了一个纯虚函数execute(),这个函数将由不同的具体策略类来实现。

class Strategy {
public:
    virtual ~Strategy() {}
    virtual void execute() = 0;
};

然后,我们可以定义多个具体的策略类,它们分别实现了execute()函数。在这里,我们为了简单起见,只定义了两个具体策略类。

class StrategyA : public Strategy {
public:
    void execute() {
        std::cout << "Strategy A is executed." << std::endl;
    }
};

class StrategyB : public Strategy {
public:
    void execute() {
        std::cout << "Strategy B is executed." << std::endl;
    }
};

最后,我们可以定义一个策略执行者类Context,它需要保存当前使用的策略对象,以及提供一个接口来

【C++设计模式】策略模式 策略模式是一种行为设计模式,它允许在运行时选择算法的行为。通过将每个算法封装到具有共同接口的独立类中,客户端可以在不改变自身代码的情况下选择要使用的算法。这使得算法可以独立于客户端变化,易于维护和扩展。策略模式通过将算法封装到独立的类中,使得算法可以在运行时动态地切换和选择。这种灵活性使得策略模式成为一种强大的设计模式,特别适用于需要经常变化或者有多种选择的算法场景。通过使用策略模式,可以提高代码的灵活性、可维护性和可扩展性,使得系统更加健壮和可靠。 阅读详情

相关推荐

C++设计模式21:策略模式

策略模式是一种行为设计模式,它允许您在运行时选择算法的行为。这种模式通过定义一系列算法,将它们封装在独立的类中,并使它们可以相互替换而不影响客户端代码的方式来实现。

琅嬛福地 1569

C++设计模式——Strategy策略模式

策略模式是一种行为型设计模式,策略模式在软件开发场景中定义了一系列的算法,并将每个算法单独封装在可替换的对象中,使应用程序在运行时可以根据具体的上下文来动态地选择和切换算法,同时保持原有的代码架构不被修改。策略模式的设计使得算法的实现与调用被分离,让算法可以独立于外部客户端进行开发和改动,使用独立的类来封装特定的算法,也避免了不同算法策略之间的互相影响。策略模式能适应多种应用场景,为了满足业务需求,应用程序在运行时可以选择不同的算法策略来达到最优的实现效果。

程序员与背包客_CoderZ 1955

COMSOL仿真分析高压直流GIS/GIL绝缘性能优化

高压直流气体绝缘设备(GIS/GIL)的绝缘性能是保障电网可靠运行的关键。通过COMSOL Multiphysics多物理场仿真,可以深入分析气固界面电场分布与电荷积聚机理。该技术结合静电场、热场和电荷传输耦合计算,能准确模拟温度梯度对SF6气体与环氧树脂界面特性的影响。工程实践中,这类仿真可优化导体结构设计、改进绝缘材料配方,并建立电场-温度关联预警模型。特别是在80℃高温工况下,仿真显示界面电荷密度会显著增加23%,这对设备安全运行具有重要指导价值。

weixin_32075843的博客 197

磁编码器选型避坑指南:为什么MT6816比霍尔传感器更适合你的伺服系统?

本文深入对比了MT6816磁编码器与传统霍尔传感器在伺服系统中的应用。MT6816基于AMR技术,对磁场方向敏感而非强度,具备高精度、强抗干扰、高安装容差和极低延时等优势,尤其适合高转速、恶劣环境下的工业场景,能有效提升系统可靠性与长期稳定性。

rainy的博客 1109

Anaconda镜像源切换全攻略:从清华源到恢复默认设置的完整流程

本文详细介绍了Anaconda镜像源的管理与优化,重点讲解了如何配置清华源以提升国内下载速度。内容涵盖镜像源工作原理、清华源详细配置步骤、多源管理策略、常见问题排查以及如何安全恢复默认设置,帮助用户构建完整的镜像源管理体系。

weixin_28828243的博客 1028

GD32F450以太网(1):ETH 外设接口简介

GD32F450以太网ETH MAC外设接口简介

Zhichao_Zhang的博客 1万+

OpenCv案例(七): 基于OpenCvSharp计算图像的清晰度(自动对焦)

自动对焦,其实是对相机成像的清晰值得计算,若对焦不清晰,成像的清晰度低,视觉效果模糊。若是在工业检测行业,对焦不准确,可能会造成严重后果;对焦准确的图像,其清晰度高,对比度鲜明,层次明显。

qq_37835727的博客 7120

C/C++李峋同款跳动的爱心代码(完整代码)

C++语言实现出李峋同款跳动的爱心的完整代码。

AIGC 10万+

企业级 Multi-Agent 实施指南:从需求拆解到上线验收的全流程方法论

本文基于12个不同行业(金融、制造、零售、互联网)的百万级Multi-Agent投产项目经验,提炼出一套可复用的全流程实施SOP,覆盖需求对齐与拆解、架构设计、开发实现、测试优化、上线部署、验收迭代6个核心阶段,包含标准化工具、量化指标、踩坑指南、可直接运行的代码示例,帮你避开90%的落地坑。需求阶段是项目成败的核心,必须对齐业务方的量化指标,明确系统边界架构设计要兼顾性能、安全、可扩展性,不要为了炫技选择复杂的框架工程化是投产的关键,测试、灰度、监控、降级机制缺一不可。

AI云原生与云计算技术学院 231

将物理信息神经网络(PINN)应用于微通道湍流的拓扑优化,并结合COMSOL数据进行训练与快速预测

本文提出一种基于物理信息神经网络(PINN)的微通道散热器流场快速预测方法。通过有限组COMSOL仿真数据训练神经网络,结合Navier-Stokes方程和能量方程作为物理约束,构建可快速预测新拓扑结构下速度场和温度场的替代模型。该方法包含数据准备、网络构建、损失函数设计等关键步骤,利用自动微分计算方程残差,显著降低传统CFD优化的计算成本,实现秒级/分钟级的流场预测,为微通道散热器拓扑优化提供高效解决方案。

huanghm88的专栏 542

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 使用ITK进行Sobel边缘检测
下一篇: 使用OpenGL实现球形环境贴图的效果是一种非常有趣的实践。下面将分享一个OpenGL实现球形环境贴图的代码示例。
普通网友
博客等级 码龄3年 312粉丝 505原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

techDM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址