状态模式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);
  }
}

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 < {
      state = new SpiteVoteState();
    } else if(oldVoteCount >= {
      state = new BlackVoteState();
    }
    state.vote(user, voteItem,this);
  }
}

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

猜你喜欢

转载自katy1206.iteye.com/blog/2029580