设计模式入门之状态模式State

//状态模式定义:
//允许一个对象在其内部状态改变时改变它的行为
//对象看起来似乎修改了它的类
//感觉状态模式在实现上跟策略模式太相似了,但是功能是不一样的
//状态模式根据状态的变化来选择相应的行为,不同的状态对应不同的类,各个实现类是平行的,但不可以相互交换
//而侧罗模式是根据需要来选择相应的实现类,各个实现类是平等的,可以相互交换
//实例:投票,根据不同的投票次数对投票者进行不同的处理
//投票状态接口
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.显示的进行状态转换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值