策略模式(1)
来源:互联网 发布:淘宝买家信誉显示7心 编辑:程序博客网 时间:2024/06/01 08:52
策略模式定义:分别封装行为接口,实现算法族,超类里放行为接口的对象,在子类里具体设定行为对象。原则就是,分离变化部分,封装接口,基于接口编程各种功能。此模式让行为算法的变化独立于算法的使用者。
策略模式注意点:
分析项目中的变化部分与不变部分
多用组合少用继承;用行为类组合,而不是行为的继承。更有弹性
案例1:
在三国杀里面,我们每个玩家都是一个独立的对象。有时候我们会抽到一些武器卡,每个对象只能持有一个武器。对于这种情况我们及时没有策略模式的概念,也会很自然的想到以下方案
1
2
3
4
5
public
interface
weapon {
public
void
attack(Player victim);
}
1
2
3
4
5
6
7
8
9
10
11
//武器:流星锤
public
class
MeteorHammer
implements
weapon {
private
final
byte
power =
2
;
private
final
byte
distance =
3
;
@Override
public
void
attack(Player victim) {
victim.beAttacked(power);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public
class
Player {
private
weapon weapon;
//生命值
private
byte
hitpoints;
//每个玩家的位置,等于在房间类中,玩家在ArrayList<Player>中的Index
private
byte
position;
public
void
attackPlayer(Player victim){
/*
* 1.首先检查距离是否可以攻击
* 2.距离允许,则攻击 weapon.attack()
*/
}
public
void
beAttacked(
byte
power){
this
.hitpoints -= power;
}
}
案例2:在HttpClient中,HttpClient提供了很多种浏览器策略,但是用户具体实例化浏览器对象时,浏览器采取何种策略,由用户自己选择。这种也是采用策略模式的思想,提取变化部分,抽象成接口,在实现其各种子类,再动态称为浏览器对象的字段
1
2
3
4
LaxRedirectStrategy laxRedirectStrategy =
new
LaxRedirectStrategy();
CloseableHttpClient httpClient = HttpClients.custom()
.setRedirectStrategy(laxRedirectStrategy)
.build();
0 0
- 策略模式(1)
- 1、策略模式(Strategy)
- 设计模式(1)—策略模式
- 设计模式1: 策略模式(Strategy)
- 设计模式(1) 策略模式
- 策略模式(政策模式) 策略枚举
- Headfirst-1策略模式
- 策略模式(Strategy) 1
- 1、Strategy策略模式
- 《1》策略模式
- 策略模式学习1
- 策略(Strategy)模式
- 策略模式(c++)
- Strategy(策略)模式
- 策略(Strategy)模式
- Strategy(策略模式)
- 策略模式(Strategy)
- 策略模式(Strategy)
- EasyUI-Tree
- MD5算法原理
- python之os模块
- lzg_ad:XPE中的EWF分区设置说明
- 羊皮书APP (Android版)开发系列(二)日志工具类
- 策略模式(1)
- HUST 1602 - Substring
- Import Projects
- 用Maven创建第一个web项目
- 记忆化搜索——地宫取宝
- ping+telnet
- 关于path_alloc 函数(APUE)
- 数据库操作
- tomcat io performance comparison with nio