设计模式学习笔记(十八)——Strategy策略模式

23种设计模式-策略(Strategy)设计模式 软考中级-软件设计师 策略设计模式 阅读详情
设计模式学习笔记(十八)——Strategy策略模式

       这段时间在项目中接触到了Strategy策略模式,所以就学习了一下,做一个总结。

       Strategy策略模式是一种对象行为模式。主要是应对:在软件构建过程中,某些对象使用的算法可能多种多样,经常发生变化。如果在对象内部实现这些算法,将会使对象变得异常复杂,甚至会造成性能上的负担。

       GoF《设计模式》中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。该模式使得算法可独立于它们的客户变化。

       Strategy模式的结构图如下:


 


      
从图中我们不难看出:Strategy模式实际上就是将算法一一封装起来,如图上的ConcreteStrategyA、ConcreteStrategyB、ConcreteStrategyC,但是它们都继承于一个接口,这样在Context调用时就可以以多态的方式来实现对于不用算法的调用。

       Strategy模式的实现如下:

       我们现在来看一个场景:我在下班在回家的路上,可以有这几种选择,走路、骑车、坐车。首先,我们需要把算法抽象出来:

       public interface IStrategy

    {

        void OnTheWay();

}

接下来,我们需要实现走路、骑车和坐车几种方式。

public class WalkStrategy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Walk on the road");

        }

    }

 

    public class RideBickStragtegy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Ride the bicycle on the road");

        }

    }

 

    public class CarStragtegy : IStrategy

    {

        public void OnTheWay()

        {

            Console.WriteLine("Drive the car on the road");

        }

}

 

最后再用客户端代码调用封装的算法接口,实现一个走路回家的场景:

class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Arrive to home");

            IStrategy strategy = new WalkStrategy();

            strategy.OnTheWay();

            Console.Read();

        }

}

运行结果如下;

Arrive to home

Walk on the road

如果我们需要实现其他的方法,只需要在Context改变一下IStrategy所示例化的对象就可以。

 

       Strategy模式的要点:

1、Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。

2、Strategy模式提供了用条件判断语句以外的另一中选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。

3、Strategy模式已算法为中心,可以和Factory Method联合使用,在工厂中使用配制文件对变化的点进行动态的配置。这样就使变化放到了运行时。

4、与Template Method相比,Strategy模式的中心跟集中在方法的封装上

 
 
设计模式 ( 十八 ) 策略模式Strategy(对象行为型) 设计模式 ( 十八 ) 策略模式Strategy(对象行为型) 1.概述 在软件开发中也常常遇到类似的情况,实现某一个功能有多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能。如查找、排序等,一种常用的方法是硬编码(Hard Coding)在一个类中,如需要提供多种查找算法,可以将这些算法写到一个类中,在该类中提供多个方法,每一个方法对应一个 阅读详情

相关推荐

Python+Flask+Echarts打造全国气象数据可视化分析大屏

本文详细介绍了如何使用Python+Flask+Echarts构建全国气象数据可视化分析大屏,实现实时监控、趋势分析和快速决策。通过Python强大的数据处理能力、Flask的轻量级优势和Echarts的交互体验,打造高效的气象数据可视化系统,提升农业、物流等行业的决策效率。

weixin_29061531的博客 1060

【设计模式——Strategy模式】

设计模式——Strategy模式

Aseed40424991的博客 546

从零抓包分析AVDTP:用Wireshark解密蓝牙音频传输全流程

本文详细介绍了如何使用Wireshark抓包工具分析AVDTP协议,解密蓝牙音频传输的全流程。从实验环境搭建到信令交互解析,再到媒体流传输深度分析,逐步揭示蓝牙音频传输的技术本质,帮助开发者深入理解AVDTP协议的工作机制。

sun99的博客 204

设计模式第2讲——策略模式(Strategy)

策略模式属于行为型设计模式。一、什么是策略模式 二、角色组成 三、优缺点四、应用场景 4.1 生活场景4.2 java场景五、代码实现5.0、UML类图5.1、VideoContext——环境类(Context)5.2、VideoStrategy——抽象策略类(Strategy)5.3、具体策略类(Concrete Strategy)5.4、TestStrategy

让~学习~成为一种习惯(橡 皮 人の技术博客) 3455

数据标注工具:AiLabel.js实现标注 超详细教程 案例分享

背景:在前端开发过程中难免遇到针对图片的缩放平移;以及在图片上进行矢量数据、文本、标注的展示;如果你有上面的任何需求,恭喜你,找到组织了.... 在此背景下,AILabel.js出生了。 前面文章我们已经介绍过AiLabel.js了; https://blog.youkuaiyun.com/u012967771/article/details/113148527 npm下载地址:https://www.npmjs.com/package/ailabel github地址:https://github.com/d.

前端互助会 9365

windows中如何将已安装的nodejs高版本降级为低版本

第一步:先清空本地安装的node.js版本 1.按健win+R弹出窗口,键盘输入cmd,然后敲回车(或者鼠标直接点击电脑左面最左下角的win窗口图标弹出,输入cmd再点击回车键) 然后进入命令控制行窗口,并输入where node查看之前本地安装的node的路径 2.找到上面找到的路径,将node.exe所在的父目录里面的所有东西都删除 3.为了彻底删除之前安装的node.js,鼠标点击电脑左面最左下角的win窗口图标弹出,输入“控制面板”再点击回车键进入,进入控制面板后,找到所安装的node.js并

weixin_44582077的博客 9万+

设计模式-策略模式 Strategy

策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。因为所有的策略类都实现相同的接口,所以,客户端代码基于接口而非实现编程,可以灵活地替换不同的策略。@Override//具体的算法...@Override//具体的算法...

weixin_46926189的博客 2279

【C++】构造函数之初始化列表(Initialization list of constructors)

本讲主要是构造函数的初始化列表的讲节,但是本节很重要,可以关乎后面写项目

m0_62599305的博客 2233

设计模式:策略模式(Strategy)

设计模式:策略模式(Strategy)

ProgramNovice的博客 1938

点到面点云配准(Point To Plane)算法知识详解和详细推导,C++代码实现

点到面 ICP (Iterative Closest Point) 是在 3D 点云配准中常见的一种变体,通过最小化点到对应面(由法向量定义的局部平面)的距离来提高收敛速度和精度。

qq_36812406的博客 1809

OpenClaw与大语言模型(Claude/GPT/MiniMax)的集成架构与最优配置策略

摘要 本文探讨了OpenClaw框架与大语言模型(Claude/GPT/MiniMax)的集成架构与优化策略。大语言模型具有强大的自然语言处理能力,但集成面临API成本、响应延迟、上下文管理等挑战。OpenClaw采用分层架构设计,包括用户界面层、对话管理层、提示工程层、模型适配层和API调用层,支持多模型切换、智能对话管理和成本控制。系统通过模型适配层实现不同API的统一调用,并提供缓存、监控等优化机制。该集成方案能够充分发挥大语言模型的优势,为本地AI助理提供更智能的服务。

一键难忘的博客 1693

设计模式 十八 策略模式Strategy 对象行为型

设计模式 十八 策略模式Strategy 对象行为型

skiwnc的博客 164

rosbag分析传感器数据的时间同步情况方法

ROS传感器时间同步分析流程:通过rosbaginfo初步检查bag文件信息,使用rqt_bag可视化时间线分布,采用rostopicecho或Python脚本提取各传感器时间戳并计算时间差统计值(均值/最大差/标准差),最后分析接收与采样时间延迟。量化评估同步精度,识别固定偏移或随机抖动问题,确保多传感器数据对齐,为后续融合处理提供可靠数据基础。

start_up_go的博客 201

设计模式之(十八)策略模式Strategy

Strategy策略模式是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类. Stratrgy应用比较广泛,比如, 公司经营业务变化图, 可能有两种实现方式,一个是线条曲线,一个是框图(bar),这是两种算法,可以使用Strategy实现. 这里以字符串替代为例, 有一个文件,我们需要读取后,希望替代其中相应的变量,然后输出.关于替代其中变量的方法可能...

weixin_33756418的博客 498

深度学习工具包 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")

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

设计模式 策略模式Strategy

设计模式 ( 十八 ) 策略模式Strategy(对象行为型) 1.概述         在软件开发中也常常遇到类似的情况,实现某一个功能有多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能。如查找、排序等,一种常用的方法是硬编码(Hard Coding)在一个类中,如需要提供多种查找算法,可以将这些算法写到一个类中,在该类中提供多个方法,每一个方法对应一个

netcaoniao的专栏 552

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

设计模式 —— 策略模式(Strategy Pattern)

策略模式(Strategy Pattern)概念 策略模式 定义了算法族,分别封装起来,让它们之前可以相互替换,此模式让算法的变化独立于使用算法的客户。 策略模式把 对象本身和运算规则 区分开来,其功能非常强大,因为这个设计模式本身的核心思想就是面向对象编程的多形性的思想。 组成策略模式 UML 图如下所示: (图片来自维基百科)策略模式将不同的算法封装成类,如上图的 ConcreteS

IT小小鸟~~ 923

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

上一篇: 设计模式学习笔记(十七)——Command命令模式
下一篇: 面向对象分析设计学习与探索(一):开篇
zhy05
博客等级 码龄21年 21粉丝 76原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值