首页 技术 正文
技术 2022年11月15日
0 收藏 853 点赞 4,099 浏览 1552 个字

来说说设计模式吧,最近开始看设计模式,觉得挺有意思的。设计模式网上的资料的挺多的,而且大部分是大家相互转来转去的。感觉也挺没有意思。我就自己写一点吧!

开始 学习设计模式,我会用自己的画的UML类图来说明问题,代码也是通过UML类图生成的。

先来看看策略模式的定义:

The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.(策略模式定义了算法族,

分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于算法的使用)。

下面是我话的最简单一种策略的UML图,没有画出调用类。(复杂一点策略模式会出现多族策略)

设计模式-策略模式(strategy pattern)

下面贴出我根据上面UML图生成的代码:

策略接口
public interface IStrategy {
public abstract void play();
}
策略的三种实现
public class StrategyA implements IStrategy {
public void play() {
System.out.println("执行了策略-------A");
}
}
public class StrategyB implements IStrategy {
public void play() {
System.out.println("执行了策略-------B");
}
}
public class StrategyC implements IStrategy {
public void play() {
System.out.println("执行了策略------C");
}
}策略上下文
public class Context {
private IStrategy strategy; public Context() { }
public Context(IStrategy strategy) {
this.strategy = strategy;
} public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
} public void display(){
strategy.play();
}
}test类:
public class Test {
public static void main(String[] args) {
Context context = new Context(new StrategyA()); //通过构造方法,注入了策略A
context.display(); Context context1 = new Context();
context1.setStrategy(new StrategyB()); //通过set方法,注入了策略B
context1.display(); Context context2 = new Context();
context2.setStrategy(new StrategyC()); //通过set方法注入了策略C
context2.display(); }
}**************************输出结果*********************************************

执行了策略——-A
执行了策略——-B
执行了策略——C

*****************************************************************************这个设计是最简单的一种了,具体复杂的我们可以想象再加入什么一些高级的东西。
最后有什么问题欢迎大家指正!!!!!!!
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860