What is the difference between the twin brother's status mode and the policy mode?

Source: Internet
Author: User

The State mode is similar to the policy mode, and their UML class diagrams are the same. This also shows that, from the code perspective, they are essentially the same, but they are actually multi-State applications. However, what they actually represent is essentially different. Which design pattern to choose represents your view of the business scenario. Abstract The business process from a reasonable perspective and select an appropriate design pattern to make the Code have a better structure.
This article focuses on my understanding of the differences between the State mode and the policy mode, and how to choose them.

I. Policy Mode

I wrote a note about the policy mode, but it was written by C. The rule mode solves the problem of multiple logic branches in the Code and takes different measures for different branches. If you are not familiar with the rule mode, you can also review it in the previous set: Pull C # Delegate and event? Policy mode? Interface callback?

Policy mode Overview

In strategy pattern, the behavior of a class or its algorithm can be changed at runtime. We create an object that represents various policies and a context object whose behavior changes with the policy object. The policy object changes the execution algorithm of the context object. This type of design pattern belongs to the behavior pattern.

Intention: Define a series of algorithms, encapsulate them one by one, and make them replaceable.
Main Solution: When multiple algorithms are similar, it is difficult to maintain the complexity caused by the use of IF... else.
When to use: A system has many classes, but what distinguishes them is their direct behavior.
Solution: Encapsulate these algorithms into one class and replace them randomly.
Key code: Implement the same interface.

Model Code of Rule Mode
  • Policy Abstraction: defines a policy interface and declares the implementation methods required for different policy schemes:
public interface Stragety {    void function();}
  • Specific policy Classes define different policy classes to implement abstract policy interfaces:
public class StrategyA implements Stragety {    @Override    public void function() {        System.out.println("invoke StrategyA function ...");    }}
public class StrategyB implements Stragety {    @Override    public void function() {        System.out.println("invoke StrategyB function ...");    }}
  • Context class:
public class Context {    private Stragety stragety;    public Context() {    }    public Context(Stragety stragety) {        this.stragety = stragety;    }    public void setStragety(Stragety stragety) {        this.stragety = stragety;    }    public void function() {        if (stragety == null) {            System.out.println("not set strategy...");            return;        }        stragety.function();    }}

The final call test code is as follows:

public class Test {    public static void main(String[] args) {        Context context = new Context();        context.function();        context.setStragety(new StrategyA());        context.function();        context.setStragety(new StrategyB());        context.function();    }}

The result is as follows:

Ii. Status Mode

The behavior in the state mode is determined by the State. In the state pattern, the behavior of the class is based on its state change. We create an object that represents various states and a context object whose behavior changes with the State object. This type of design pattern also belongs to the behavior pattern.

Status mode Overview

Intention: Allows an object to change its behavior when its internal state changes. The object seems to have modified its class.

Main Solution: The behavior of an object depends on its state (attribute), and its related behavior can be changed according to its state change.

When to use: The Code contains a large number of condition statements related to the object state.

Solution: Abstracts various specific state classes.

Key code: One or more methods are usually used in the status mode interface. In addition, the status mode implementation class methods, generally return values, or change the value of instance variables. That is to say, the State mode is generally related to the object state. Methods of implementation classes have different functions, covering methods in interfaces. The State mode is the same as the policy mode. It can also be used to remove the IF... else and other condition selection statements.

Status mode model code
  • State abstraction. Define a state interface to declare the methods to be implemented in different States:
public interface State {    void function1();    void function2();}
  • The specific status class defines different status classes to implement the abstract interface of status:
public class StateA implements State {    @Override    public void function1() {        System.out.println("invoke StateA function1 ...");    }    @Override    public void function2() {        System.out.println("invoke StateA function2 ...");    }}
public class StateB implements State {    @Override    public void function1() {        System.out.println("invoke StateB function1 ...");    }    @Override    public void function2() {        System.out.println("invoke StateB function2 ...");    }}
  • Context class:
public class Context {    private State state;    public Context() {    }    public Context(State originalState) {        this.state = originalState;    }    public void setState(State state) {        this.state = state;    }    public void setStateA() {        setState(new StateA());    }    public void setStateB() {        setState(new StateB());    }    public void function1() {        state.function1();    }    public void function2() {        state.function2();    }}

The final call test code is as follows:

public class Test {    public static void main(String[] args) {        Context context = new Context();        context.setStateA();        context.function1();        context.function2();        context.setStateB();        context.function1();        context.function2();    }}

The result is as follows:

Iii. Differences between status mode and Policy Mode

Through the comparison of the above model code, some people may find that, at first glance, there is almost no difference between the two, and they are playing with the syntactic sugar of polymorphism. This reminds me of the example in the first chapter of the typical book refactoring to improve the design of existing code. The refactoring article contains the following --

The switch statement can be replaced by polymorphism, but because a video can modify its category within the lifecycle, an object cannot modify its class within the lifecycle. Therefore, the rule mode cannot be used to replace the switch with polymorphism, but the state mode should be used ). Is this a state mode or a strategy mode? The answer depends on whether the price class represents the billing method or a certain state of the video.

That is to say, the abstract Choice Policy mode or state mode for a scenario depends on your understanding of this scenario. My understanding is strategy, that is, method. Different policy implementation classes share the same method, and their status should be equal. For example, if you choose to eat bread for breakfast or rice for Chinese food, this is the policy decision; if you choose to take a bus or subway for transportation; if you choose to speak Chinese in China, select to speak English in the United States...

Status migration is usually accompanied by transition, that is, State migration. It may be a State migration in time series or a behavior (calling a method) in a certain state, to another State. It should focus on State migration. For example, the water temperature can be regarded as the State during the water burning process; the Mobile Phone Mobile Data Bluetooth WiFi switch, the speed of car driving; Chinese when speaking in China, speaking English in the United States... can be abstracted into states. Wait !!! In China, I chose to speak Chinese, and in the United States I chose to speak English. Are they abstracted into a policy mode or a state mode?

In fact, it depends on how you think about this scenario. You should regard it as an equal scenario between the two parties, but make a choice in different scenarios, it can be abstracted into a policy model. If you treat China and the United States as two States, and the two States can be converted, for example, in China, when a plane flew to China and its status changed to China, we should consider abstracting it into a State model.

  1. In the state transition scenario, it is best not to directly change the state (not absolutely impossible) by the client, but to cause State migration caused by some other operations on the client, in other words, it is recommended that the client not directly create an Instance Object of the specific state implementation class and set it through the setstate () method.
  2. State conversion may also be caused by the internal behavior of the object.

In this case, the status mode code implementation is different from the policy mode code implementation. Next I will modify the status mode model code based on the above ideas.
For example, the client executes the Actionb method to change the status to Stateb. For the second point, assume that when function2 is executed in the Stateb state, the status is changed to statea. The Code is as follows:

  • Define a Status interface:
public interface State {    void function1();    void function2(Context context);}
  • Specific Status classes:
public class StateA implements State {    @Override    public void function1() {        System.out.println("invoke StateA function1 ...");    }    @Override    public void function2(Context context) {        System.out.println("invoke StateA function2 ...");    }}
public class StateB implements State {    @Override    public void function1() {        System.out.println("invoke StateB function1 ...");    }    @Override    public void function2(Context context) {        System.out.println("invoke StateB function2 ...");        context.setStateA();    }}
  • Add a method that may change the status in other operations and encapsulate it as an interface:
public interface Others {    void actionB();}
  • Context class:
Public class context implements others {private State state; public context () {}// mark -------- mark1 public context (State originalstate) {This. state = originalstate;} // mark it as -------- mark2 public void setstate (State state) {This. state = State;} public void setstatea () {setstate (New statea ();} public void setstateb () {setstate (New Stateb ();} public void function1 () {state. function1 ();} public void function2 () {state. function2 (this) ;}@ override public void Actionb () {system. out. println ("INVOKE Actionb... "); setstateb ();}}

The final call test code is as follows:

public class Test {    public static void main(String[] args) {        Context context = new Context();        context.setStateA();        context.function1();        context.actionB();        context.function1();        context.function2();        context.function1();        context.function2();    }}

The execution result is as follows:

Iv. Summary

In the real world, strategy and state are two completely different ideas. Although the State and Policy modes have similar structures, although they are based on the open and closed principles, their intentions are completely different. When we model the status and policy, this difference will lead to completely different problems. State migration is a core component of state modeling. State mode helps objects manage the state. State migration has nothing to do with this when selecting a policy. In addition, the Policy mode allows a customer to select or provide a policy, which is completely absent in the state mode. Therefore, in the state mode, to avoid insecure client operations, we can leave the Code markedMARK1And mark the codeMARK2Method of private.

From the code, we can understand: WHO promotes behavior changes. In status mode, status transfer is managed by context or State itself. If you manage state transfer in state, it must hold the reference of context. For example, in the code above, the Stateb function2 () method needs to call the setstate () method to change its state, and it needs to input a context parameter. In the policy mode, strategy never holds the reference of context, and the client passes the selected strategy to context. Because the status mode and Policy mode are used in many work scenarios (I have used them in my recent project), This article focuses on analyzing the similarities and differences between the status mode and the policy mode, to deepen my understanding of them. I also hope to help my friends who are interested in seeing this article.

What is the difference between the twin brother's status mode and the policy mode?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.