《研磨设计模式》chap18 状态模式state(3)应用到场景
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap18 状态模式state(3)应用到场景
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public interface 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);}System.out.println("你有惡意刷票行為,取消投票資格");}
}public class RepeatVoteState implements VoteState{public void vote(String user, String voteItem, VoteManager voteManager) {//重復投票//暫時不做處理System.out.println("請不要重復投票");}
}public class NormalVoteState2 extends NormalVoteState{public void vote(String user, String voteItem, VoteManager voteManager) {//先調用已有的功能super.vote(user, voteItem, voteManager);//給予積分獎勵,示意一下System.out.println("獎勵積分10分");}
}public class BlackWarnVoteState implements VoteState{public void vote(String user, String voteItem, VoteManager voteManager) {//待進黑名單警告狀態System.out.println("禁止登錄和使用系統3天");}
}public class VoteManager {//持有狀態處理對象 private VoteState state = null;//記錄用戶投票的結果,Map<String,String>對應Map<用戶名稱,投票的選項> private Map<String,String> mapVote = new HashMap<String,String>();//記錄用戶投票次數,Map<String,Integer>對應Map<用戶名稱,投票的次數> private Map<String,Integer> mapVoteCount = new HashMap<String,Integer>();// 獲取記錄用戶投票結果的Map public Map<String, String> getMapVote() {return mapVote;}//投票 public void vote(String user,String voteItem){//1:先為該用戶增加投票的次數//先從記錄中取出已有的投票次數Integer oldVoteCount = mapVoteCount.get(user);if(oldVoteCount==null){oldVoteCount = 0;}oldVoteCount = oldVoteCount + 1;mapVoteCount.put(user, oldVoteCount);//2:判斷該用戶投票的類型,就相當于是判斷對應的狀態//到底是正常投票、重復投票、惡意投票還是上黑名單的狀態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);}
}public class Client {public static void main(String[] args) {VoteManager vm = new VoteManager();for(int i=0;i<8;i++){vm.vote("u1", "A");}}
}
總結
以上是生活随笔為你收集整理的《研磨设计模式》chap18 状态模式state(3)应用到场景的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《研磨设计模式》chap18 状态模式s
- 下一篇: 《研磨设计模式》chap18 状态模式s