//状态模式定义:
//允许一个对象在其内部状态改变时改变它的行为
//对象看起来似乎修改了它的类
//感觉状态模式在实现上跟策略模式太相似了,但是功能是不一样的
//状态模式根据状态的变化来选择相应的行为,不同的状态对应不同的类,各个实现类是平行的,但不可以相互交换
//而侧罗模式是根据需要来选择相应的实现类,各个实现类是平等的,可以相互交换
//实例:投票,根据不同的投票次数对投票者进行不同的处理
//投票状态接口
public interface VoteState {
public void vote(String user, String voteItem, VoteManager voteManager);
}
//正常投票类
public class NormalVoteState implements VoteState {
public void vote(String user, String voteItem, VoteManager voteManager) {
voteManager.getMapVote().put(user, voteItem);
System.out.println("恭喜你投票成功");
}
}
//重复投票类
public class RepeatVoteState implements VoteState {
public void vote(String user, String voteItem, VoteManager voteManager) {
System.out.println("请不要重复投票");
}
}
//恶意投票类
public class SpiteVoteState implements VoteState {
public void vote(String user, String voteItem, VoteManager voteManager) {
String s = voteManager.getMapVote().get(user);//取消投票记录
if(s! == null) {
voteManager.getMapVote().remove(user);
}
System.out.println("你有恶意投票行为,取消投票资格");
}
}
//黑名单投票类
public class BlackVoteState implements VoteState {
public void vote(String user, String voteItem, VoteManager voteManager) {
System.out.println("进入黑名单,讲禁止登录和使用该系统");
}
}
//上下文(环境),投票管理类
public class VoteManager {
private VoteState state = null;
private Map<String, String> mapVote = new HashMap<String, String>();
private Map<String, String> mapVoteCount = new HashMap<String, Integer>();
public Map<String, String> getMapVote() {
return mapVote;
}
public void vote(String user, String voteItem) {
Integer oldVoteCount = mapVoteCount.get(user);
if(oldVoteCount == null) {
oldVoteCount = 0;
}
oldVoteCount = oldVoteCount + 1;
mapVoteCount.put(user, oldVoteCount);
if(oldVoteCount <= 1) {
state = new NormalVoteManager();
}else if(oldVoteCount < 5) {
state = new ReapeatVoteState();
}else if(oldVoteCount <8) {
state = new SpiteVoteState();
}else if(oldVoteCount >= 8 ) {
state = new BlackVoteState();
}
state.vote(user, voteItem, this);
}
}
//测试
public class Client {
public static void main(String[] args) {
VoteManager vm = new VoteManager();
for(int i=0; i<8; i++) {
vm.vote("ul", "A");
}
}
}
//由上边的实例可以看出,投票管理类中还是不可避免得使用了if-else多重判断语句
//状态模式本质:根据状态来分离和选择行为
//模式优缺点
//1.简化应用逻辑控制
//2.更好地分离状态和行为
//3.更好的扩展性
//4.显示的进行状态转换
设计模式入门之状态模式State
最新推荐文章于 2024-09-06 07:00:00 发布