策略模式

策略模式详解 1.简介 在现实生活中长长遇到实现某种目标存在多种策略可供选择的情况,例如,出行旅游可以乘坐飞机、乘坐火车、骑自行车或自己开私家车等,超时促销可以采用打折、送商品、送积分等方法。 在软件开发中也常常遇到类似的情况,当实现某一个功能存在多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能,如数据排序策略有冒泡排序、选择排序、插入排序、二叉树排序等。 如果使用多重条件转移语句实现(即硬编码),不但使条件语句变得很复杂,而且增加。删除或更换算法要修改原代码,不易维护,违背开闭原则。如 阅读详情

策略基本解释:
①谋略;手段:讲究策略。 ②与“战略”相对。为实现战略任务而采取的手段。既有稳定性,又有较大的灵活性,随着客观形势的变化而变化。
策略字意解释摘自 http://xh.5156edu.com/html5/z71m35j166307.html

如:去市中心,可以骑自行车,搭公交,搭地铁,驾车
策略模式:接口 + 实现类
如果你的if else像下面这样臃肿,快用策略模式重构它

public class StrategyTest {
	
		public static void main(String[] args) {
		String toolName = "Bicycle";
//		String toolName = "Bus";
//		String toolName = "Metro";
//		String toolName = "Car";
		timeConsuming(toolName);
	}
	
	public static void timeConsuming(String tool) {
		if("Bicycle".equals(tool)) {
			//这里代替复杂的业务代码
			System.out.println("骑自行车到市中心需耗时2小时");
		}else if("Bus".equals(tool)) {
			System.out.println("搭公交车到市中心需耗时1小时");
		}else if("Metro".equals(tool)) {
			System.out.println("搭地铁到市中心需耗时50分钟");
		}else if("Car".equals(tool)) {
			System.out.println("驾车到市中心需耗时45分钟");
		}
		//else if ...
	}

}

在这里插入图片描述

创建接口

public interface WalkingTool {
	
	public void timeConsuming();

}

创建实现类

public class Bicycle implements WalkingTool {

	public void timeConsuming() {
		System.out.println("骑自行车到市中心需耗时2小时");
	}

}
public class Bus implements WalkingTool {

	public void timeConsuming() {
		System.out.println("搭公交车到市中心需耗时1小时");
	}

}
public class Car implements WalkingTool {

	public void timeConsuming() {
		System.out.println("驾车到市中心需耗时45分钟");
	}

}
public class Metro implements WalkingTool {

	public void timeConsuming() {
		System.out.println("搭地铁到市中心需耗时50分钟");
	}

}

改造后调用

public class StrategyTest {
	
	public static void main(String[] args) {
		//WalkingTool tool = new Bicycle();
		WalkingTool tool = new Bus();
		//WalkingTool tool = new Metro();
		//WalkingTool tool = new Car();
		tool.timeConsuming();
	}
		
}

运行结果
在这里插入图片描述

如何使用C#自带的GDI+双缓冲类BufferedGraphics实现双缓冲功能 小白摸索着编写一个上位机界面,将遇到的问题及解决方法记录下,以供后来的小白使用哈。这篇文章解决的问题是在绘图时候的闪烁问题。其中网上有些介绍的设置控制方式controlstyle的方法,这个方法我的理解是比较适合于在一个完整的窗口当中绘图。如果要在一个窗口当中的内部容器或者控件内画图的话就不太适合,通常按照前述的方法设置后没有任何效果。对于在窗口内部的绘图的来说,比较有效的方法是在内存当中开辟一块 阅读详情

相关推荐

新出的智谱GLM-4.7很牛逼?

Zhipu AI(智谱)最近发布的 GLM-4.7 再次刷新了开源大模型的天花板。作为一款约 400B 参数规模的 MoE 模型,它不仅在传统的代码与推理任务上超越了 DeepSeek-V3.2 和 Kimi-K2 等强力对手,更通过**“保留思考(Preserved Thinking)”和“交错思考(Interleaved Thinking)”**等架构级创新,重新定义了 Agentic Workflow 的设计范式。

kakaZhui的博客 2397

java策略模式

目录 1 策略模式概述 2 策略模式的结构与实现 1. 模式的结构 2. 模式的实现 3 策略模式的应用实例 通用实现 报价管理的例子 策略和上下文的实例 1 策略模式概述  策略这个词应该怎么理解,打个比方说,我们出门的时候会选择不同的出行方式,比如骑自行车、坐公交、坐火车、坐飞机、坐火箭等等,这些出行方式,每一种都是一个策略。   再比如我们去逛商场,商场现在正在搞活动,有打折的、有满减的、有返利的等等,其实不管商场如何进行促销,说到底都是一些算法,这些算法本身只是一种策略,并且这

mocas_wang的博客 4514

STM32CubeMX——循迹传感器TCRT5000的使用

前言 人生如逆旅,我亦是行人。 ————苏轼《临江仙·送钱穆父》 一、介绍 TCRT5000描述:(带有晶体管输出的反射光学传感器) TCRT5000是一种反射式光学传感器,它包括一个红外发射器和一个3.5mm引线封装的光电晶体管,可阻挡可见光。还具有1mA 典型被测输出电流,2.5mm峰值工作距离,可应用传感与仪表,工业等行业。 TCRT5000具有紧凑的结构,其中发射光源和探测器布置在同一方向,通过使用来自物体的反射红外光束来感知物体的存在。工作波长为950毫米,探测器由光电晶体管组成

W_Oilpicture的博客 1万+

策略模式的实现

策略模式就像是在餐厅点餐的过程。假设你和朋友一起去餐厅,你们可以根据自己的口味选择不同的菜肴。你可以点披萨,你的朋友可以点汉堡,而另一位朋友可以点沙拉。每个人都可以根据自己的喜好选择不同的策略(菜肴),但最终都能满足吃东西的需求。

Hardy Army的博客 1284

ArcGIS小白必看:5分钟搞定shp矢量文件分割(附常见错误排查)

本文为ArcGIS新手详细解析了分割shp矢量文件的四种核心方法:裁剪工具、分割工具、按属性选择导出及ArcPy脚本自动化。重点强调了投影匹配等关键步骤,并提供了常见错误排查指南,帮助用户快速掌握矢量数据分割技巧,提升GIS数据处理效率。

h9j8k7l6m5n的博客 800

RTAB-map:实时高效的SLAM库

Real‐time appearance‐based mapping (RTAB‐Map)是一种基于外观的闭环检测方法,具有良好的内存管理,以满足处理大场景和在线长周期管理要求。RTAB‐Map集成了视觉和激光雷达SLAM方案,并支持目前绝大多数的传感器 是一个强大的、开源的Simultaneous Localization and Mapping(SLAM)库,专为机器人和无人驾驶领域设计。它提供了一套完整的解决方案,用于构建三维地图,并在未知环境中进行实时定位与导航。 github项目地址 RTAB-

weixin_45761399的博客 1万+

策略模式详解以及在spring中策略模式的两种简化应用

策略模式,同样可以消除掉繁杂的if else ,那么它和简单工厂模式的区别在哪? 简单工厂模式是根据传入的参数返回不同的产品,不同的产品内部封装了不同的逻辑。 策略模式类似,但是策略模式内部是封装了算法,也就是封装了某一种策略。 举个例子,超市活动打折优惠,1.普通计费。 2.满300减20 3.满400减80 4.满500打八折 如果用简单工厂模式,那么需要定义四个产品子类,如果将来又新增了...

hello world 7782

高云FPGA系列教程(8):ARM串口数据接收(中断和轮询方式)

GW1NSR-4C ARM部分共有2个串口外设,都挂载在APB1总线上,最高支持波特率921.6Kbit/s,无奇偶校验位,8位数据位,1位停止位,支持高速测试模式 HSTM(High Speed Test Mode),即每个时钟周期输出1位数据,可以在短时间内传输大量数据。官方手册上没有描述发送和接收缓存FIFO的深度,所以不确定是否支持缓存。

whik1194的博客 1685

【python】策略模式

策略模式。抽空学习下常见的20几种设计模式,python2.7来设计实现。基本就根据某设计模式书籍来实现python版本。希望能坚持下来全部介绍完。

weixin_42660118的博客 2624

SwiftUI 5 教程之 SwiftData使用入门(教程含源码)

对我来说,记住日期很难。是的,您可以设置该日期的提醒,但该提醒无法产生紧迫感。让我们创建一个应用程序,我们可以在其中添加将来发生的事件。如果我们可以在主应用程序上看到所有即将发生的活动,那就太好了。也许将它们添加到小部件上以营造紧迫感。对于任何事件,我们需要跟踪哪些事情?我们将在下一篇文章中添加更多属性,其中我们将讨论迁移。现在,这就是我们所需要的。开始吧。

iCloudEnd的博客 987

PCL 使用RANSAC拟合平面【2026最新版】

RANSAC拟合平面算法原理和实现流程详解以及最大迭代次数和内点期望概率的设置方法。最后再对拟合后的平面法向量与向量(1,1,1)进行定向。博客长期更新,最近一次更新时间为:2026年4月24日。

点云侠的博客 42万+

策略模式&lambda重构策略模式

文章目录一、概念以及背景二、策略模式三、lambda重构策略模式三、拓展Java8提供的内置函数式接口 一、概念以及背景 策略模式(Strategy Pattern):定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户端而变化,也称为政策模式(Policy)。 简而言之,策略模式是客户端在运行时选择某种解决方案(策略,方法,算法)来解决问题,而解决方...

一砖一瓦 896

C#上位机开发揭秘:从新手到大神的蜕变之路,代码实例全解析!

上位机通常是与硬件设备(如嵌入式系统、PLC、传感器等)进行通信的计算机程序。它的作用是通过某种通信协议(如串口、TCP/IP 等)向设备发送命令,并接收设备的反馈数据。上位机需要有一个图形用户界面(GUI)来展示数据或控制硬件设备。通过本篇教程,我们介绍了 C# 上位机开发的基本步骤,从串口通信的实现,到图形用户界面的构建,再到进阶功能的实现。作为上位机开发的新手,掌握这些基础知识是非常重要的。而随着经验的积累,你可以逐步尝试更复杂的功能,比如多线程处理、数据分析与存储等。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 4832

23种策略模式之策略模式

在软件开发中,设计模式是为了解决常见问题而提供的一套可重用的解决方案。策略模式(Strategy Pattern)是其中一种常见的设计模式,它属于行为型模式。该模式的核心思想是将不同的算法封装成独立的策略类,使得它们可以相互替换,而不影响客户端的使用。策略模式与其他设计模式有一些明显的区别。与模板方法模式相比,策略模式强调算法的灵活性,允许在运行时切换不同的策略。与状态模式相比,策略模式更注重不同算法之间的替换性,而非状态的内部转换。策略Context(上下文)

一码归一码@ 1899

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

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

【深入设计模式】策略模式—策略模式详解及策略模式在源码中的应用

详解策略模式,并深入策略模式再源码中的应用

SK_Jaco的博客 1357

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

策略模式总结

文章目录策略模式一、什么是策略模式二、为什么要去使用策略模式三、框架中有哪些用到模板模式和策略模式四、项目实践中的策略模式实现五、总结1、策略模式的优缺点 策略模式 一、什么是策略模式 ​ 策略模式(Strategy Pattern),一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。 ​ 策略模式适合于以下应用场景: 1)、许多类的区别仅在于其具体实现行为不同; 2)、需要动态的在几个算法中选择一个。 传统策略模式介绍: https://www.runoob.com/design

小发发的博客 768

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java策略模式_Java设计模式之策略模式详解

本文实例为大家分享了Java策略模式,供大家参考,具体内容如下1、策略模式(Strategy Pattern)是一种比较简单的模式,也叫做政策模式(PolicyPattern)。定义如下:Define a family of algorithms,encapsulate each one,and make them interchangeable.(定义一组算法,将每个算法都封装起来,并且使它们之...

weixin_42355744的博客 1959

前端策略模式

前端策略模式 文章目录前端策略模式一、策略模式有什么用二、策略模式的定义二、策略模式有什么用1.引入库2.读入数据总结 一、策略模式有什么用 策略模式主要是为了实现开闭原则,减少面条代码里面大量的写if…else 二、策略模式的定义 定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。 二、策略模式有什么用 1.引入库 代码如下(示例): import numpy as np import pandas as pd import matplotlib.pyplot as plt import

qq_39406460的博客 1773
上一篇: SpringBoot2.x整合Swagger2
下一篇: CentOS 7之Redis4.0.14安装
l_learning
博客等级 码龄8年 15粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值