`

设计模式(17)- 状态模式

阅读更多

状态模式

1.定义

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

2.示例代码

        代码演示了对投票行为的相应处理。

  

/*封装一个投票状态的相关行为*/
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 SpiteVoteState 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,String>();
   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);
   }
}

   

/*客户端调用投票*/
public class Client{
    public static void main(String agr[]){
        VoteManager vm = new VoteManager();
        for(int i=0;i<0;i++){
           vm.vote("u1","A");
        }
    }
}

3.实际应用

      状态模式可以简化控制逻辑,但是也有个很明显的缺点,一个状态对应一个处理类,会使得程序引入太多的状态类,这样程序变得杂乱。

 

状态模式的本质:根据状态来分离和选择行为
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics