策略模式【Strategy Pattern】

3.4 策略模式(Strategy Pattern) -《SSM深入解析与项目实战》 文章目录3.4 策略模式(Strategy Pattern)3.4.1 策略模式的定义3.4.2 策略模式的作用3.4.3 模式结构3.4.4 场景实例抽象策略角色具体的策略角色上下文角色测试类演示结果总结 3.4 策略模式(Strategy Pattern) 遇到一个问题,可能有各种各样的不同解决方式,在这里,可以把方式称为策略。在实际中,根据不同的场景或者条件来选择不同的策略解决问题。也比如说,我们在实际开发中,可能我们实现某个功能有几种不同的方式,在这个时候,我们就可以使用策略模式来进行选 阅读详情

刘备要到江东娶老婆了,走之前诸葛亮给赵云(伴郎)三个锦囊妙计,说是按天机拆开解决棘手问题,嘿,还别说,真是解决了大问题,搞到最后是周瑜陪了夫人又折兵呀,那咱们先看看这个场景是什么样子的。先说这个场景中的要素:三个妙计,一个锦囊,一个赵云,妙计是小亮同志给的,妙计是放置在锦囊里,俗称就是锦囊妙计嘛,那赵云就是一个干活的人,从锦囊中取出妙计,执行,然后获胜,用 JAVA 程序怎么表现这个呢?我们先看类图:


三个妙计是同一类型的东东,那咱就写个接口:

package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 首先定一个策略接口,这是诸葛亮老人家给赵云的三个锦囊妙计的接口
*
*/
public interface IStrategy {

 	//每个锦囊妙计都是一个可执行的算法
	public void operate();
} 
然后再写三个实现类,有三个妙计嘛:

package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 找乔国老帮忙,使孙权不能杀刘备
*/
public class BackDoor implements IStrategy {
public void operate() {
 System.out.println("找乔国老帮忙,让吴国太给孙权施加压力");
 }
}
package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 求吴国太开个绿灯
*/
public class GivenGreenLight implements IStrategy {
public void operate() {
 System.out.println("求吴国太开个绿灯,放行!");
 }
}
package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 孙夫人断后,挡住追兵
*/
public class BlockEnemy implements IStrategy {
public void operate() { 
 System.out.println("孙夫人断后,挡住追兵");
 }
} 

好了,大家看看,三个妙计是有了,那需要有个地方放这些妙计呀,放锦囊呀:

package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 计谋有了,那还要有锦囊
*/
public class Context {
//构造函数,你要使用那个妙计
private IStrategy straegy;
public Context(IStrategy strategy){
 this.straegy = strategy;
 }

//使用计谋了,看我出招了
public void operate(){
 this.straegy.operate();
 }
} 
然后就是赵云雄赳赳的揣着三个锦囊,拉着已步入老年行列的、还想着娶纯情少女的、色迷迷的刘老爷子去入赘了,嗨,还别说,小亮的三个妙计还真是不错,瞅瞅:

package com.cbf4life.strategy;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
*/
public class ZhaoYun {
/**
 * 赵云出场了,他根据诸葛亮给他的交代,依次拆开妙计
 */
public static void main(String[] args) {
 Context context; 

 //刚刚到吴国的时候拆第一个
 System.out.println("-----------刚刚到吴国的时候拆第一个-------------");
 context = new Context(new BackDoor()); //拿到妙计
 context.operate(); //拆开执行
 System.out.println("\n\n\n\n\n\n\n\n");

 //刘备乐不思蜀了,拆第二个了
 System.out.println("-----------刘备乐不思蜀了,拆第二个了-------------");
 context = new Context(new GivenGreenLight());
 context.operate(); //执行了第二个锦囊了
 System.out.println("\n\n\n\n\n\n\n\n");

 //孙权的小兵追了,咋办?拆第三个
 System.out.println("-----------孙权的小兵追了,咋办?拆第三个
-------------");
 context = new Context(new BlockEnemy());
 context.operate(); //孙夫人退兵
 System.out.println("\n\n\n\n\n\n\n\n");

 /*
 *问题来了:赵云实际不知道是那个策略呀,他只知道拆第一个锦囊,
 *而不知道是BackDoor这个妙计,咋办? 似乎这个策略模式已经把计谋名称写出来了
 *
 * 错!BackDoor、GivenGreenLight、BlockEnemy只是一个代码,你写成first、second、
third,没人会说你错!
 *
 * 策略模式的好处就是:体现了高内聚低耦合的特性呀,缺点嘛,这个那个,我回去再查查
 */
 }
} 
就这三招,搞的周郎是“陪了夫人又折兵”呀!这就是策略模式,高内聚低耦合的特点也表现出来了,还有一个就是扩展性,也就是 OCP 原则,策略类可以继续增加下去,只要修改 Context.java 就可以了,这个不多说了,自己领会吧。


策略模式(Strategy Pattern)详解 策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法封装起来,并使它们可以互相替换。策略模式让算法独立于使用它的客户端而变化,使得客户端可以在不修改代码的情况下,通过组合不同的策略对象来改变应用的行为。策略模式的核心思想是:“定义一系列算法,封装每一个算法,并使它们可以互换。”在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的上下文对象。策略对象改变上下文对象的执行算法。在以下情况下,策略模式特别有用:当需要在运行时选择不同的算法时:策略模式允许客户端在运行时选择不同的算法实 阅读详情

相关推荐

第二次 PX4仿真环境搭建过程全记录

参考链接 https://blog.youkuaiyun.com/yanwumuxi/article/details/80097294 https://www.ncnynl.com/archives/201709/2013.html 一、安装依赖项 我们使用Debian / Ubuntu LTS 作为Linux的标准支持版本,但是也支持Cent OS 和 Arch Linux的发行版本。 权限设置 警告:永远...

移步换景的博客 2261

策略模式(Strategy Pattern)

OO基础: 抽象,封装,多态,继承 OO原则: 1.封装变化, 2.多用组合,少用继承 3.针对接口编程,而不是针对实现编程。 策略模式(Strategy Pattern): 定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法...

weixin_30471561的博客 578

ROS四旋翼无人机快速上手指南(3):工作环境文件框架与各功能包整体讲解

这一章节主要讲解无人机平台的控制文件架构和各个功能包组成和用法。

The Road of Engineer 2404

Strategy Pattern(策略模式)

相关连接:https://blog.youkuaiyun.com/knowledgebao/article/details/84986637 策略模式 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对...

knowledgebao的博客 246

OpenHarmony自定义Launcher

OpenHarmony源码版本:4.0release开发板:DAYU / rk3568DevEco Studio版本:4.0.0.600切换分支为OpenHarmony-4.0-Release,并下载源码。

Abner_Crazy的博客 1630

统信UOS V20 安装mysql5.7.42详细教程

到bin/下,执行下面的命令,初始化mysql服务信息,得到数据库的初始密码,实际如果目录不一样记得换成自己的目录。下载后通过远程将安装包上传至服务器,我这里将安装包上传至/usr/local/mysql 下。ps:这时候如果还是不能远程访问的话,可能是防火墙的原因,命令行执行以下命令即可。再次登录,发现缺少 libtinfo.so.5文件,再次建立软连接。登录,发现报错,提示缺少libncurses.so.5文件,使用。创建 /var/lib/ 下mysql目录。登录成功,修改密码,设置远程访问。

为谁伫立在风中 1万+

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

策略模式,是我们接触到的第一个设计模式,也是较容易理解的一个模式。 我们可以给它下一个定义: 定义了算法族,分别封装起来,让它们之间可以互相转换,此模式让算法的独立于使用算法的客户。 维基百科上的定义是: a software design pattern that enables an algorithm's behavior to be selected at runtime. 维

desperate_liu的博客 448

Altium Designer应用技巧1: 功能模块的复用方法

Altium Designer应用技巧1: 功能模块的复用方法      我们在使用Altium Designer进行电路图设计时,常会遇到功能模块的复用问题,例如我们经常需要将12V以DC-DC的方式转换成5V,这在很多线路板上都会应用到。现在我们普通的做法是,每个板子都重新绘制一遍,像这样DC-DC的电路,很浪费时间。那么如何采用提高工作效率呢?我们可以采取Altium Desi

snmplink的博客 1万+

策略模式-Strategy Pattern

1. 主要优点 策略模式的主要优点如下: (1) 策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为。 (2) 策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族,恰当使用继承可以把公共的代码移到抽象策略类中,从而避免重复的代码。 (3) 策...

weixin_33696106的博客 157

科研问答:医药类本科生(临床、中医、中药与护理)本科阶段是否需要开展科研学习?

医药类本科生(临床、中医、中药与护理)本科阶段是否需要开展科研学习?

MD Code 1507

第2章: MMU Notifier 全局通知器的核心原理⭐

摘要 MMU Notifier机制是Linux内核中用于处理内存地址空间变化通知的关键框架。其设计遵循解耦与标准化、最小侵入性、高性能和安全性四大原则,采用三层架构实现上层应用、核心层与内存管理层的协作。框架提供两种通知模型:全局订阅的mmu_notifier和区间订阅的mmu_interval_notifier,分别适用于KVM虚拟化和GPU共享虚拟内存等不同场景。核心数据结构mmu_notifier_ops定义了设备驱动需要实现的回调函数集合,包括进程退出处理、页面老化管理、地址范围失效通知等功能。

图形/计算GPU的驱动与虚拟化技术分享园地 4556

策略模式 Strategy Pattern

策略模式「strategy pattern 」(也称为policy pattern)是一种行为软件设计模式「behavioral」,可以在运行时选择算法。代码不是直接实现单个算法,而是接收运行时指令,指示使用一系列算法「a family of algorithms」中的哪一个。在上面的UML类图中,Context类不直接实现算法。相反,Context引用 用于执行算法的Strategy接口(Strategy.algorithm()),这使得Context独立于算法的实现方式。

DachuiLi的博客 1359

OpenClaw第2章:快速安装

本章将手把手教你安装 OpenClaw。

Maynor的博客 3236

设计模式-19策略模式Strategy Pattern

策略模式是一种行为设计模式,通过定义一系列可互换的算法并将其封装,使算法能独立于使用它的客户端而变化。该模式适用于需要动态切换不同算法或行为的场景,可避免大量条件判断语句。其核心结构包括策略接口、具体策略类和使用策略的上下文类。实现时,先定义策略接口,然后创建具体策略类实现接口方法,最后通过上下文类动态设置和切换策略。示例展示了支付系统中的多种支付策略(信用卡、PayPal、银行转账)的灵活切换,体现了策略模式的可扩展性和解耦优势。 (149字)

d3y1`5 81_09 1087

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

策略模式 (Strategy Pattern)

策略模式 (Strategy Pattern)

sanmansan的博客 5276

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

策略模式(Strategy Pattern)

相信大家对于if-else if-else 应该再也熟悉不过,也肯定曾经想过如何去减少使用不必要的if-else if-else 和switch这样的条件语句,学习了策略模式之后,你会发现原来代码还可以更简洁。 一、策略模式概述 策略模式(Strategy Pattern)也有叫做政策模式(Policy Pattern)的 是一种比较简单的行为型模式——定义一组算法,将每个算...

东境物语 1110

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

【设计模式】策略模式(Strategy Pattern)详解

策略模式(Strategy Pattern)是一种行为型设计模式,

qq_59344127的博客 1839

策略模式Strategy Pattern

<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; ms...

weixin_34104341的博客 1137

策略模式(Strategy Pattern)就这么简单

0x00 举个生活中的例子某个大人网站是会员制的,金牌会员购买精神食粮打7折,银牌会员打8折,铜牌会员打9折,铁牌会员不打折。也就是说不同的用户在购买精神食粮的时候结算的价格是不一样的,即使你们买相同公司出品的相同食粮,你们的总价格是不一样的,因为根据会员等级不同,有不同的折扣。也就是说,面对不同会员等级的用户,大人网站会有不同的计价算法。问过度娘的人都知道,假如你经常问度娘哪里有可堪一撸的资源,此

人王的专栏 6831

Spring框架之策略模式 (Strategy Pattern)

策略模式是软件设计中的一大利器,掌握它可以让你的代码更具灵活性和可扩展性,是应对变化和复杂度的重要手段之一。

欢迎来到我的博客!这里是一个专注于计算机技术的分享平台,涵盖编程开发、算法研究、系统架构、软件工程等多个领域。无论你是初学者还是资深开发者,都能在这里找到有价值的内容。 1942
上一篇: TCP接入层的负载均衡、高可用、扩展性架构
下一篇: 代理模式【Proxy Pattern】
涛濤
博客等级 码龄12年 136粉丝 92原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值