当前位置:网站首页>Application of state mode in JSF source code

Application of state mode in JSF source code

2022-07-08 01:16:00 Mengqi D Xiaowu

Behavioral patterns

Catalog

1、 The state pattern

1.1 The state pattern UML chart

1.2 Look at the state mode and application examples in daily life

1.3 Java Code implementation

2、JSF State mode embodiment in source code

3、 Advantages and disadvantages of state mode

3.1 advantage

3.2 shortcoming

3.3 Use scenarios

3.4 matters needing attention

4、 summary

4.1  Key points of state mode

4.2  Comparison between state mode and policy mode


1、 The state pattern

In state mode (State Pattern) in , The behavior of a class changes based on its state . In state mode , We create objects that represent various states and a behavior that changes as the state object changes context object .

  • Intention : Allows an object to change its behavior when its internal state changes , Object appears to modify its class .
  • Main solution : The behavior of an object depends on its state ( attribute ), And it can change its behavior according to its state .
  • When to use : The code contains a large number of conditional statements related to the state of the object .
  • How to solve : Abstract all kinds of concrete state classes .
  • Key code : Usually there is only one method in the interface of command mode . There are one or more methods in the state mode interface . and , The implementation of the state pattern class method , General return value , Or change the value of the instance variable . in other words , State mode is generally related to the state of an object . Methods that implement classes have different functions , Override the methods in the interface . The state mode is the same as the command mode , It can also be used to eliminate if...else Wait for the conditional choice statement .

1.1 The state pattern UML chart

1.2 Look at the state mode and application examples in daily life

  1. In the big talk design mode, you are in good condition at work in the morning 、 I want to sleep at noon 、 Gradually recover in the afternoon 、 Working overtime is hard . This is a change of state , At different times , There will be different states .
  2. Take water for example , Three states of water , solid 、 Liquid 、 gas , The three states show different characteristics and behaviors , The transformation between them is also accompanied by thermodynamic phenomena .
  3. The elevator , There is a running state 、 Open the door 、 Closed state 、 Stop state, etc
  4. A day's own state from morning to night , Such as working state 、 Learning state and so on
  5. Athletes can be in normal condition 、 Abnormal state and overlong state

1.3 Java Code implementation

According to the above UML chart

First, let's define a State Abstract state class , It defines an interface to encapsulate And Context The behavior associated with a particular state of ;

/**
 *  Abstract state class 
 * @author gh
 *
 */
public abstract class State {
    
    public abstract void Handle(Context context);
}

Then go to declare another ConcreteState Specific status class , Each subclass implements an and Context A state of related behavior .

public class ConcreteStateA extends State{
 
    @Override
    public void Handle(Context context) {
        context.setState(new ConcreteStateB()); // Set up A The next state of the game is B
        
    }
 
}
class ConcreteStateB extends State{
 
    @Override
    public void Handle(Context context) {
        context.setState(new ConcreteStateA()); // Set up B The next state of the game is A
    }
    
}

Context class , Maintain a ConcreteState Instances of subclasses , This instance defines the current state

/**
 *  Define the current state 
 * @author gh
 *
 */
public class Context {
    State state;
 
    public Context(State state) { // Definition Context Initial state of 
        super();
        this.state = state;
    }
 
    public State getState() {
        return state;
    }
 
    public void setState(State state) {
        this.state = state;
        System.out.println(" The current state is "+state);
    }
    public void request(){
        state.Handle(this); // Process the request and point to the next state 
    }
}

Mention state mode , It reminds me of workflow , Workflow is to control the state of a node to achieve node jump , Finally, control the process .

If a leave process is initiated above , At this time, the first node is the approval of department leaders , Department leaders will continue to move forward after approval , If not, there are two states , One is to reject the request directly , The leader said , The project is in a hurry recently , No one can ask for leave , The other is that your leave application is wrong , We need to return it for rectification and rewrite it . After passing the audit, enter the next node , Reviewed by human resources department , Of course, human resources can also reject the request , Or ask you to rectify , After the HR review is passed, you can take a vacation , At this time, you can also choose whether to send Email.

/**
 *  Node interface 
 * @author gh
 *
 */
public abstract class Node {
    private static String name; // Current node name 
    // Node jump 
    public abstract void nodeHandle(FlowContext context);
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    
}

amount to State class , A node name is maintained here .

/**
 *  Leadership node 
 * 
 * @author gh
 * 
 */
public class LeadNode extends Node {
    @Override
    public void nodeHandle(FlowContext context) {
        // According to the status of the current process , To control the direction of the process 
        // First, judge whether the process is over 
        if(!context.isFlag()){
        System.out.println(context.getMessage()); // Read the application first 
        if(context!=null&&3==context.getStatus()){ // Only in the applied state can the department leader review it 
            // Set the name of the current node 
            setName(" Manager Zhang ");
            // Add audit opinion 
            context.setMessage(context.getMessage()+getName()+" Approved by ;");
            // Approved by 
            context.setStatus(0); // Pass the audit and point to the next node 
            context.setNode(new HrNode());
            context.getNode().nodeHandle(context);
        }
    }else{
        System.err.println(" The process is over ");
        }
    }
}

A leader node is created here , It is used to maintain the process of leadership review , Approval will be given to HR to examine ;

public class HrNode extends Node {
 
    @Override
    public void nodeHandle(FlowContext context) {
        // First, judge whether the process is over 
        if(!context.isFlag()){
        //  According to the status of the current process , To control the direction of the process 
        if (context != null &&
                0 == context.getStatus()) { // Only after the approval of the higher level can it be HR to examine 
            //  Set the name of the current node 
            setName("HR Li ");
            // Read the audit content of the upper level and add your own opinions 
            System.out.println(context.getMessage()+getName()+" Approved by ");
            //  Approved by 
            context.setStatus(0); //HR Pass the audit and point to the next node  , Set the state to end if there is no next node 
            context.setFlag(true);
            
        }
        }else{
            System.out.println(" The process is over ");
        }
    }
 
}

here HR Pass the audit and set the node to the end state ;

/**
 *  Process control 
 * 
 * @author gh
 * 
 */
public class FlowContext {
    private boolean flag; //  Represents the end of the process 
    /**
     *  Process status  0: adopt  1: rejected  2. Return for rectification  3. Has applied for 
     * 
     */
    private int status;
 
    private String message; //  news 
    private Node node; //  Node information 
    public boolean isFlag() {
        return flag;
    }
 
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
 
    public int getStatus() {
        return status;
    }
 
    public void setStatus(int status) {
        this.status = status;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    public Node getNode() {
        return node;
    }
 
    public void setNode(Node node) {
        this.node = node;
    }
 
    public static boolean start(FlowContext context) {
        Node node = new LeadNode();
        context.setNode(node); //  Set the initial node 
        context.setStatus(3); //  Set the status to pending 
        context.getNode().nodeHandle(context); //  Initiate request 
        //  Finally, we need to know whether the application is successful 
        // Judge that the current is the last node and pass the audit , And the process is over 
        if("HR Li ".equals(node.getName())&&0==context.getStatus()&&context.isFlag()){
            System.out.println(" Approved by , End of the process ");
            return true;
        }else{
            System.out.println(" The audit failed , The process is over ");
            return false;
        }
    }
 
    public FlowContext() {
        super();
    }
    
}

A process control class is maintained here , It will be HR and LEAD The node is passed after , And they maintain their own nodes .
Finally write a test class to test :

public static void main(String[] args) {
    FlowContext context=new FlowContext();
       context.setMessage(" I, Wang Xiaoer , Because there's something in the eleven , So take three more days off , I hope the company can pass the audit ");
    context.start(context); 
 }

The results are as follows
I, Wang Xiaoer , Because there's something in the eleven , So take three more days off , I hope the company can pass the audit
I, Wang Xiaoer , Because there's something in the eleven , So take three more days off , I hope the company can pass the review of manager Zhang ;HR Li checked and approved
Approved by , End of the process ;

The above example just imitates the jump of workflow control state . The main advantage of state mode is to put the judgment and control of state in the server , So that the client does not need to write a lot of code judgment , To control their own node jump , And if it does , We can deal with each node separately , When the process flows to a certain node , You can write your own node flow method . Of course, there are many disadvantages of state mode , For example, the coupling of classes is relatively high , Basically, three classes should be written at the same time , And a lot of node classes will be created .

2、JSF State mode embodiment in source code

JSF It is a classic front-end framework , It doesn't matter if you haven't used it , Here is just an analysis of its design idea .

stay JSF in , The processing of all pages is divided into 7 Stages , Is defined in PhaseId Class , Different constants are used to represent the periodic stages , Source code is as follows .

private class PhaseId implements Comparable {
    ...
    private static final PhaseId[] values = {
        ANY_PHASE,    //  Any life cycle stage 
        RESTORE_VIEW,    //  Restore view stage 
        APPLY_REQUEST_VALUES,    //  Application request value stage 
        PROCESS_VALIDATIONS,    //  Process the input verification phase 
        UPDATE_MODEL_VALUES,    //  Update the value stage of the model 
        INVOKE_APPLICATION,    //  Call the application stage 
        RENDER_RESPONSE    //  Show response phase 
    };
    ...
}

The switching of these States is Lifecycle Class execute() Method , One parameter will be passed in FacesContext object , Eventually all States are FacesContext preservation . Don't analyze it in depth here .

package javax.faces.lifecycle;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;

public abstract class Lifecycle {
    public Lifecycle() {
    }

    public abstract void addPhaseListener(PhaseListener var1);

    public abstract void execute(FacesContext var1) throws FacesException;

    public abstract PhaseListener[] getPhaseListeners();

    public abstract void removePhaseListener(PhaseListener var1);

    public abstract void render(FacesContext var1) throws FacesException;
}

3、 Advantages and disadvantages of state mode

3.1 advantage

  1. Encapsulates the transformation rules .
  2. Enumerate possible states , You need to determine the state type before enumerating the States .
  3. Put all the behaviors related to a state into a class , And it's easy to add new states , Just changing the state of the object can change the behavior of the object .
  4. Allows state transformation logic to be integrated with state objects , Instead of a huge conditional block . The structure is clear , Avoid too much switch…case or if…else Use of statements
  5. You can have multiple environment objects share a state object , So as to reduce the number of objects in the system .

3.2 shortcoming

  1. The use of state patterns will inevitably increase the number of system classes and objects . There will be too many subclasses , That is, class expansion
  2. The structure and implementation of state patterns are complex , Improper use will lead to confusion of program structure and code .
  3. State mode pair " Opening and closing principle " The support is not very good , For a state mode that can switch states , Adding a new state class requires modifying the source code responsible for state transformation , Otherwise, you cannot switch to the new state , In addition, to modify the behavior of a state class, you need to modify the source code of the corresponding class .

3.3 Use scenarios

  • A scene in which behavior changes as states change
  • Conditions 、 A substitute for a branch judgment statement

3.4 matters needing attention

  • State mode can be used when behavior is constrained by state , The state of the object should not exceed 5 individual

4、 summary

Through the example above , We already know something about state patterns , Now let's make a summary , Let's review our state mode :

1. State mode allows an object to change its behavior when its internal state changes , Object appears to modify its class .
    understand : This pattern encapsulates the state into separate classes , And delegate the action to the object representing the current state , That is to say, the behavior will change with the internal state .
   “ It looks as if its class has been modified ” What does that mean ? From the customer's point of view : If the object you use can completely change its behavior , Then you will feel , This object is actually instantiated from another class . However , actually , You know we're using composition to create the illusion of class change by simply referring to different state objects

4.1  Key points of state mode

  • (1) Customers do not interact with States , Overall understanding of the status is context The job of
  • (2) In state mode , Each state is by holding Context References to , To achieve state transition
  • (3) Using state patterns always increases the number of classes in the design , This is to achieve program scalability , The price of flexibility , If your code is not one-off , Different states may be added in the later stage , Then the design of state mode is absolutely worth it .【 It is also a disadvantage 】
  • (4) State classes can be more than one context The instance Shared

4.2  Comparison between state mode and policy mode

First, let's see more similarities between them :

  1. Adding new states or policies is easy , And there's no need to modify the Context object .
  2. They all make your code conform to OCP principle ( Software should be developed for extensions , The modification should be closed ). In state mode and policy mode ,Context Object is off for modification , Add a new status or policy , No need to modify Context.
  3. As in state mode Context There will be an initial state , The policy mode also has a default policy .
  4. State patterns encapsulate different behaviors in different states , The policy pattern encapsulates different behaviors with different policies .
  5. They all rely on subclasses to implement related behaviors

The difference between the two models lies in their ” Intention “ Different :

State mode helps objects manage state , We encapsulate a group of behaviors into early state objects ,context The behavior of can be delegated to one of those states at any time . Over time , The current state changes in the set of state objects , To reflect context Internal state , therefore ,context Your behavior will also change . When you want to add a new state , There is no need to modify the original code and add a new state class . The policy mode allows Client Choose different behaviors . By encapsulating a set of related algorithms , by Client Provide runtime flexibility .Client Available at run time , Choose any algorithm , Without changing the algorithm Context. Some examples of popular strategy patterns are writing code that uses algorithms , For example, encryption algorithm 、 Compression algorithm 、 Sorting algorithm . The customer usually designates context Which strategy object is to be combined .

In a word : The most fundamental difference is that the strategy model is a variety of solutions to the same problem , There is no connection between these different solutions ; The state mode is different , State patterns require that states be related to each other , In order to achieve state transition .

 

Reference article :

http://c.biancheng.net/view/8493.html

https://www.jianshu.com/p/5bf844141687

https://www.runoob.com/design-pattern/state-pattern.html

https://www.cnblogs.com/xyzq/p/11090344.html

原网站

版权声明
本文为[Mengqi D Xiaowu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130545511634.html