状态模式State根据状态来分离和选择行为

本文探讨了状态模式在实现投票管理系统中的应用,详细解释了如何通过状态变化来调整投票行为,包括普通投票、重复投票、恶意投票和禁止投票等不同场景。通过实例代码展示了如何根据投票次数改变投票状态,进而实现对投票行为的有效管理和控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

状态模式的功能就是分离状态的行为,通过维护状态的变化,来调用不同状态对应的不同功能。

状态决定行为。

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);
}
}

public class RepeatVoteState implements VoteState {
public void vote(String user,String voteItem,VoteManager voteManager){

}
}

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);
}
}
}

public class BlackVoteState implements VoteState {
public void vote(String user,String voteItem,VoteManager voteManager){

}
}

public class VoteManager {
private VoteState state = null;

private Map<String, String> mapVote = new HashMap<String, String>();

private Map<String, Integer> 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 += 1;
mapVoteCount.put(user, oldVoteCount);

if(oldVoteCount == 1) {
state = new NormalVoteState();
} else if(oldVoteCount > 1 && oldVoteCount < 5) {
state = new RepeatVoteState();
} else if(oldVoteCount >= 5 && oldVoteCount < 8) {
state = new SpiteVoteState();
} else if(oldVoteCount >= 8) {
state = new BlackVoteState();
}
state.vote(user, voteItem,this);
}
}

客户端代码:
VoteManager vm = new VoteManager();
for(int i = 0;i < 8;i++) {
vm.vote("ul","A");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值