Design Patterns strategy mode and state mode (strategy pattern & state pattern)

This paper compares the two structures to explain the behavior of similar design patterns: Strategy mode and state mode. Both individual understanding and learning are relatively intuitive and simple, but the actual use of it is not good practice, be difficult to use design patterns to learn it. This is also the reason for the introduction of both on together, through examples and comparative description, I believe it should be some of the more profound perception. Finally, the combination of personal experience simply talk about some of the views of these two modes.

1. The concept model

1.1 Strategy Pattern

Run-time behavior or algorithm changes and the like, so as to achieve the purpose of modifying its function;

Usage scenarios:  a system needs to dynamically choose one of several algorithms, but these algorithms are only different between their behavior. Also too much decision-making process occurs if else, you can also consider using this mode.

Implementation: These algorithms may be packaged as such a separate operation, be replaced by a user as desired.

Advantages:  more flexible, scalable, and avoid a lot of if else structure.

Disadvantages:  Foreign exposed the class of all actions and algorithms, resulting in excessive behavior policy class expansion.

1.2 Status Mode

Runtime class behavior by its state decisions;

Usage scenarios:  the object-dependent charging behavior changes depending on the state change scenario, or if else a large number of branch structure and the like;

Implementation: The state of the object classes into a single package, each state in the transaction processing state, and controlling the state transition to another state;

Advantages:  easy to add new state, the state transition rule package, each state may be multiplexed shared with and, if else avoid large structure.

Disadvantages:  The model structure and achieve a relatively complex, resulting in excessive increase in the state the number of objects and classes. At the same time due to the transfer to other states controlled by each state, plus the new state must be modified to join an existing part of the state to take effect in the state machine.

1.3 similarities

By both behavior and state split into a series of smaller components, the replacement function conditions and states, so that in line with the principle of opening and closing, easy expansion. Also available as an if or else an alternative branch; maximum supported behavior and state are limited;

1.4 difference

  • Strategy Mode, the function of the class is to take the initiative to change based on current conditions;
  • State mode, a passive function class is changed by the current state;
  • No association between each action or policy mode algorithm;
  • Association between the status mode state, the state itself and the state transition control;

2. Principle

Very similar to the structure of the two modes, respectively, FIG UML class look at the following two design patterns:

Strategy Mode UML 2.1

description:

Context:

Use some kind of strategy, specific policy decisions by their behavior included, the class can take the initiative to modify the policy to use in order to change their behavior;

Strategy:

Abstract strategy class that defines a common interface for all supported algorithms;

ConcreteStrategy:

Context specific strategies can be used;

UML 2.2 state mode

description:

Context:

With a status flag class, which determines the behavior of its current state, the state transition is controlled by a class state;

State:

Abstract state class, for defining the status of all the public interface Context;

ConcreteState:

A particular state of some Context class, including transaction processing and controlling state transition in this state to him;

3. Example - Strategy Pattern

For example compression software uses different compression strategies.

 

Abstract strategy interfaces: Compression

public interface Compression {
    public void doCompression();
}

Fast Compression Algorithm: Rapid

public class Rapid implements Compression {
    @Override
    public void doCompression() {
        System.out.println("Use rapid compression strategy!");
    }
}

Efficient compression algorithms: Efficient

public class Efficient implements Compression {
    @Override
    public void doCompression() {
        System.out.println("Use efficient compression strategy!");
    }
}

Encryption compression algorithm: Encrypt

public class Encrypt implements Compression {
    @Override
    public void doCompression() {
        // TODO Auto-generated method stub
        System.out.println("Use encrypt compression strategy!");
    }
}

Integrated above the compression algorithm software: WinRAR

public class WinRAR {
    
    private Compression compression = null;
    
    public WinRAR(Compression compression) {
        this.compression = compression;
    }
    
    public void setStrategy(Compression compression) {
        this.compression = compression;
    }
    
    public void compression() {
        if (compression != null) {
            compression.doCompression();
        }
    }
}

Demo:

public class Demo {
    public static void main(String[] args) {
        WinRAR winrar = new WinRAR(new Rapid());
        winrar.compression();
        winrar.setStrategy(new Efficient());
        winrar.compression();
        winrar.setStrategy(new Encrypt());
        winrar.compression();
    }
}

result:

Use rapid compression strategy!
Use efficient compression strategy!
Use encrypt compression strategy!

This example looks very intuitive, the latter will give a little analysis and personal understanding.

4. Example - state model

We use the model to describe the state through the work process of automatic washing machines.

For simplicity, we will only consider [Start] -> [work] -> [end], these three states.

Following its first look at the UML class diagram:

Abstract state of the interface: State

public interface State {
    public void doJob(Washing washing);
}

Start status: Start

public class Start implements State {
    @Override
    public void doJob(Washing washing) {
        System.out.println("Start Washing Clothes!");
        washing.setState(new Work());
        washing.request();
    }
}

Work status: Work

public class Work implements State{
    @Override
    public void doJob(Washing washing) {
        System.out.println("Working Now!");
        washing.setState(new End());
        washing.request();
    }
}

End state: End

public class End implements State{
    @Override
    public void doJob(Washing washing) {
        System.out.println("All Finished!");
        washing.setState(null);
    }
}

Washing machine category: Washing

public class Washing {
    private State state = null;
    
    public void setState(State state) {
        this.state = state;
        if (state == null) {
            System.out.println("Current state: null!");
        }
        else {
            System.out.println("Current state: " + state.getClass().getName());
        }
    }
    
    public void request() {
        if (state != null) {
            state.doJob(this);
        }
    }
}

Demo:

public class Demo {
    public static void main(String[] args) {
        Washing washing = new Washing();
        washing.setState(new Start());
        washing.request();
    }
}

result:

Current state: state.Start
Start Washing Clothes!
Current state: state.Work
Working Now!
Current state: state.End
All Finished!
Current state: null!

washing provides the primary interface used by the user. Initially, the user uses a washing configuration state, and can send commands to the washing, the subsequent user need not directly deal with the particular transient. Each state will automatically transfer control to the next state, until the end of the run.

5. Summary

Talk about personal strategies for some understanding of design patterns and status patterns (not necessarily right, just some thoughts):

5.1 Strategy Mode:

a) frequent use if else could seriously consumption performance

Strategy mode is more suitable for, conduct classes often work in any mode, instead of switching will be based on random conditions.

For example, the APP development process, certain functions will depend on the state of the screen anyway, so we need to use if else are judged in each frame of the current screen is horizontal or vertical screen, then the next step of the process?

Obviously, this would seriously consumption performance, the correct approach is to deal with horizontal and vertical screen split into two strategies, each time the screen is switched, active cut what mode to use;

b) Not all branches of if else and can use the strategy pattern instead

For the above example compression software, the user will choose a pattern, then the following work, this is no problem.

But if we provide is a compression command, which can pass parameters using different compression methods, it is necessary to use if else, because we do not know what the user would input parameters, what mode.

c) no policy strategy mode

Core strategy pattern is split into a series of operations to a number of wheels may be individually reusable, under a specific condition wherein they are directly used, instead of passing conditions to use if else conditional judgment to perform the corresponding operations.

From this perspective, the policy mode unworthy of the name, it is not only intelligent, rational decision-making based on current conditions, but also requires the user to choose a proactive strategy execution. This has advantages, but it also becomes more no strategy.

The actual development process, we all want each other to provide the interface easy to use, the best one interface can get all the problems, because the caller, I do not care about your implementation, I only care about the simple use this interface to finish my It needs.

The fundamental reason lies in its break encapsulation, exposed concrete strategy, which is an unavoidable problems caused by its splitting component scalable at the same time, policy decisions by the executive model will advance to the caller, the code is flexible and scalable at the same time brings it is inconvenient to use.

If the strategy pattern is to avoid a lot of if else decision-making, then the language supports it can use hashtable, respectively, condition and function objects as key, value directly to select corresponding operation according to the conditions. Particularly suitable for a large number of branches.

Therefore, the actual development process need to weigh according to their actual situation.

5.1 Strategy Mode:

Core state model is a state of each object are to be done for each individual object processing state, and controls transition to other states by their state; Behavior class only provides user-friendly interface outwardly;

Extended state is not particularly friendly, we need to modify the transfer of other states. Secondly, its implementation is more flexible, with good error-prone.

summary:

Strategy mode is active replacement strategy to be used by the object itself to reach decisions Context aim to change behavior, change the current passive mode transition to State Object state by state, changing the state occurs at runtime.

A policy package pattern in advance each set may alternate family of algorithms, to deal with a suitable selection of the dynamic needs and the state mode processing under different conditions, different problems Context object behavior;

Guess you like

Origin www.cnblogs.com/yssjun/p/11116652.html