"JAVA and Model" state mode

At the beginning "and the JAVA mode" Shi Yan Hongbo book describes the state (State) mode:

State model, known as the state of the object pattern (Pattern of Objects for States), the state of behavior pattern model object.

Mode when the state allows an object to change its internal state to change their behavior. This looks like the object is to change its class the same.

Configuration state pattern
  sentence to express the state pattern to study the behavior of objects in the package objects in different states, each state object belongs to a subclass of an abstract state class. The intention is to make the state a model object changes in its internal state when their behavior has changed. State pattern class diagram schematically as follows:
  Here Insert Picture Description
character status mode are involved:

● Environment (Context) role, as is also the context: the interface definition client is interested in, and retain a particular instance of the state class. Examples of this particular class is given the state of the current state of the object in this environment.

● abstract state (State) Roles: defining an interface for a particular package environment status (Context) corresponding to the target behavior.

● specific state (ConcreteState) role: every concrete state classes implement the environment (Context) in a state corresponding behavior.

Source
  environment class role

public class Context {
    //持有一个State类型的对象实例
    private State state;

    public void setState(State state) {
        this.state = state;
    }
    /**
     * 用户感兴趣的接口方法
     */
    public void request(String sampleParameter) {
        //转调state来处理
        state.handle(sampleParameter);
    }
}

Abstract state class

public interface State {
    /**
     * 状态对应的处理
     */
    public void handle(String sampleParameter);
}

Specific Status Class

public class ConcreteStateA implements State {

    @Override
    public void handle(String sampleParameter) {
        
        System.out.println("ConcreteStateA handle :" + sampleParameter);
    }

}
public class ConcreteStateB implements State {

    @Override
    public void handle(String sampleParameter) {
        
        System.out.println("ConcreteStateB handle :" + sampleParameter);
    }

}

Client class

public class Client {

    public static void main(String[] args){
        //创建状态
        State state = new ConcreteStateB();
        //创建环境
        Context context = new Context();
        //将状态设置到环境中
        context.setState(state);
        //请求
        context.request("test");
    }
}

As can be seen from the above, the behavior of Environmental Context request () is assigned to a particular state of a class. By using the principle of polymorphism, can dynamically change the contents of the property of the State Environmental Context, and converting from pointing to a specific state category to another point class state, so that the behavior of the environment class request () of a particular state by different class to perform.

Usage scenarios
  consider the application of an online voting system, to achieve the same user can only control one vote, if a user repeatedly vote, and the number of voting more than 5 times, it is determined that a malicious brush votes, vote to disqualify the user, of course, he must also cancel the votes cast; if the number of times a user vote more than 8 times, will enter the blacklist, ban then log in and use the system.

To use the state pattern implementation, you first need to define the various states out of the voting process, according to the above description is broadly divided into four states: normal voting, repeated voting, malicious brush votes, into the blacklist. Then create a poll management object (the equivalent of Context).

The system configuration diagram as follows:
  Here Insert Picture Description
  source
  abstract class state

public interface VoteState {
    /**
     * 处理状态对应的行为
     * @param user    投票人
     * @param voteItem    投票项
     * @param voteManager    投票上下文,用来在实现状态对应的功能处理的时候,
     *                         可以回调上下文的数据
     */
    public void vote(String user,String voteItem,VoteManager voteManager);
}

Specific class status - normal Vote

public class NormalVoteState implements VoteState {

    @Override
    public void vote(String user, String voteItem, VoteManager voteManager) {
        //正常投票,记录到投票记录中
        voteManager.getMapVote().put(user, voteItem);
        System.out.println("恭喜投票成功");
    }

}

Specific class state - repeat vote

public class RepeatVoteState implements VoteState {

    @Override
    public void vote(String user, String voteItem, VoteManager voteManager) {
        //重复投票,暂时不做处理
        System.out.println("请不要重复投票");
    }

}

Specific state class - a malicious brush votes

public class SpiteVoteState implements VoteState {

    @Override
    public void vote(String user, String voteItem, VoteManager voteManager) {
        // 恶意投票,取消用户的投票资格,并取消投票记录
        String str = voteManager.getMapVote().get(user);
        if(str != null){
            voteManager.getMapVote().remove(user);
        }
        System.out.println("你有恶意刷屏行为,取消投票资格");
    }

}

Specific class status - Blacklist

public class BlackVoteState implements VoteState {

    @Override
    public void vote(String user, String voteItem, VoteManager voteManager) {
        //记录黑名单中,禁止登录系统
        System.out.println("进入黑名单,将禁止登录和使用本系统");
    }

}

Environmental

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;
    }
    /**
     * 投票
     * @param user    投票人
     * @param voteItem    投票的选项
     */
    public void vote(String user,String voteItem){
        //1.为该用户增加投票次数
        //从记录中取出该用户已有的投票次数
        Integer oldVoteCount = mapVoteCount.get(user);
        if(oldVoteCount == null){
            oldVoteCount = 0;
        }
        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);
    }
}

Client class

public class Client {

    public static void main(String[] args) {
        
        VoteManager vm = new VoteManager();
        for(int i=0;i<9;i++){
            vm.vote("u1","A");
        }
    }

}

Results are as follows:
Here Insert Picture Description
As can be seen from the above example, the transition state are basically internal behavior, the main mode to maintain the internal state. For example, for people to vote, at any time of his operations are to vote, but the voting process is not necessarily the same as managed objects, the state will be judged according to the number of votes, and then to choose different treatment depending on the state.

Recognized state mode
  ● state and behavior

The so-called state of the object, generally refers to the value of the attribute of the object instance; refers to the behavior of the object function, and then specifically, may correspond to the behavior of most of the methods.

Functional status pattern of behavior that is separated from the state, by maintaining a state of change, to call different states corresponding to different functions. In other words, state and behavior are associated, their relationship can be described as: state decided to act.

Since the state is changed at runtime, so that behavior can also be changed at runtime based on state changes.

● parallelism behavior

Note that parallel lines rather than equality. The so-called parallelism refers to the behavior of each state in which the level is the same, independent of each other, there is no association, which is to decide in the end to go a parallel lines according to different states. Behavior is different, of course, the corresponding implementations are also different from each other is not replaceable.
  Here Insert Picture Description
  And emphasized that equality can be an alternative, they are different descriptions of the same act or achieve, so in the event of the same behavior, you can choose to implement any of the appropriate treatment according to the conditions.
  Here Insert Picture Description
  You may find that the structure of the state structure and mode of strategy pattern is exactly the same, but they aim to achieve, but the essence is completely different. There are also behavioral characteristics between the state model and strategy mode is a very important difference between the behavior of the state model are parallel in nature, can not replace each other; and conduct policy mode is equal in nature, it can be interchangeable.

● environment and the state of the processing target

In the state mode, the environment (Context) is held by the state of the object, but the environment (Context) itself does not deal with state-dependent behavior, but the functions entrusted to the processing status of state corresponds to the state of processing class to handle.

Often need to acquire environment (Context) own data processing in a specific state category, even in the method of correction will be necessary when the environment (Context), and thus, typically ambient (Context) itself as a parameter passed to a particular state processing class.

The client generally and the environment (Context) interaction. The client can be used to configure a status object environment (Context), Once configured, you no longer need and to deal with the state of the object. The client is usually not responsible for maintaining the state of operation during follow-up in the end is not responsible for deciding which state a specific object using the process.

Article from: https://www.cnblogs.com/java-my-life/archive/2012/06/08/2538146.html

Guess you like

Origin blog.csdn.net/weixin_41490593/article/details/90513003