Comparison of state patterns and policy patterns in Java design pattern programming _java

Source: Internet
Author: User

To correctly use state and policy patterns in Java applications, developers need to be aware of the differences between the two patterns. Although the structure of the state and policy patterns is very similar, they also follow the open and closed principle, representing the solid design principles of the ' O ', but their intentions are completely different. The policy pattern in Java is to encapsulate a set of related algorithms, providing the caller with run-time flexibility. The caller can choose a different algorithm at run time without modifying the context class that uses the policy. Classic examples of using policy patterns include implementing cryptographic algorithms, compression algorithms, and sorting algorithms. On the other hand, the state pattern uses an object to behave differently in different states. Objects in the real world are also stateful, and they will behave differently depending on the state, such as vending machines, which can only be sold in a hascoin state, and will not sell if you don't put a coin in it. Now you can see clearly the difference between the policy pattern and the state pattern, and their purpose is different. A state pattern can help an object manage its state, whereas a policy pattern allows clients to choose different behaviors. Another difference that is not easy to see is who is going to drive behavior changes. In the policy mode, it is client-driven, which provides different policies for contextual information, whereas in state mode, state migration is managed by the context or by its own object. Similarly, if you are modifying the state in the States object, it must hold a reference to the context, which means that for the vending machine, it can invoke the SetState method to modify the state of the current situation. On the other hand, the policy object does not hold a reference to the context, and its clients pass the selected policy to the context. The policy pattern and state mode are the most easily encountered questions about the Java design pattern, and in this article on Java design patterns, we will describe this in detail. We will explore the similarities and differences between the two patterns, which will help to improve your understanding of the two patterns.

Similarities between state and policy patterns:
If you look at the UML diagram of the policy and state patterns, they look very similar. In state mode, the object that uses the states object to change the behavior is called the context object, and similarly in the policy pattern, the object that uses the strategy object to alter the behavior is also the condition object. Remember, the client interacts with the context object. In state mode, the context proxies the state object's method invocation, and the current object in context is the specific state object, while in the policy pattern, the context operation is also a policy object, which is either passed in as a parameter, It is either provided when the context object is created.

Let's look at some similarities between the two core Java design patterns:

State and policy patterns are easy to add new states or policies without affecting the context object that uses them
Both modes follow the open and closed design principles, which means that your design is opened to the extension and turned off for modification. In both modes, context changes are closed, new states or policies, you do not need to modify the context objects in other states, or only minor changes are required.
Just as the context object in the state mode has an initial state, the context in the policy pattern usually has a default policy.
The state pattern encapsulates different behaviors in the manner of different state objects, and the policy pattern encapsulates different behaviors with different policy objects.
Both of these schemas rely on specific subclasses to implement specific behaviors. Each specific policy is extended from an abstract policy class, and each state is a subclass of an interface or abstract class that represents the state.


State Mode Instance

 public class WindowState {private String statevalue; 
  Public WindowState (String statevalue) {this.statevalue = Statevalue; 
  Public String Getstatevalue () {return statevalue; 
  } public void Setstatevalue (String statevalue) {this.statevalue = Statevalue; The public void handle () {/* * * * operates differently depending on the state, and then toggles the status/if (window. Equals (Statevalue)) {SWI 
      Tchwindow (); 
    This.statevalue = "full Screen"; 
      else if ("full Screen". Equals (Statevalue)) {Switchfullscreen (); 
    this.statevalue = "Window"; 
  } private void Switchwindow () {System.out.println ("Toggle to Window State"); 
  private void Switchfullscreen () {System.out.println ("Toggle to Full-screen State"); } 
   
} 
/** 
 * Status of the use of * * Public 
class Windowcontext { 
  private windowstate state; 
   
  Public Windowcontext (WindowState state) { 
    this.state = state; 
  } 
   
  Public WindowState getState () {return state 
    ; 
  } 
   
  public void SetState (WindowState state) { 
    this.state = state; 
  } 
   
  public void Switchstate () { 
    this.state.handle (); 
  } 
} 

 
 /* state mode behavior mode * Change the state of the 
 object and change the behavior of the object 
 * According to state, change behavior/ 
 public 
class Test { 
  public static void Main (string[] args) { 
    * 
     * * The state value of this example is only two, controlled by the state class itself 
     * can also control the state value to the client to set 
    * * Windowcontext context = new Windowcontext (New WindowState ("window")); 
    Context.switchstate (); 
    Context.switchstate (); 
    Context.switchstate (); 
    Context.switchstate (); 
 
  } 
 

Print

Toggle window State Switch to full screen state switch to 
full Screen state 


Policy Pattern Instance

/** 
 * Merchandise Promotion 
 * This class is: the type of cash charged/public 
interface Icashsuper { 
   double acceptcash (double); 
} 
/** 
 * Normal cash charge 
 * @author Stone 
 */public 
class Cashnormal implements Icashsuper { 
 
  @ Override public 
  Double Acceptcash (double) {return money 
    ; 
  } 
 
} 

/** 
 * Cash on sale 
 * @author Stone 
 */public 
class Cashrebate implements Icashsuper { 
  private double rebate; Discount public 
  cashrebate (double rebate) { 
    this.rebate = rebate; 
  } 
 
  @Override public 
  Double Acceptcash (double) {return 
    new BigDecimal (Money * rebate/10). Setscale (2, Bigde Cimal. ROUND_HALF_UP). Doublevalue (); 
  } 
   
   
 


/** 
 * Profit return now charged Cash 
 * @author Stone * * */Public 
class Cashreturn implements Icashsuper { 
  private Double moneycondition; Return limit amount 
  private double returnmoney//Return amount public 
  Cashreturn (double moneycondition, double Returnmoney) { 
    this.moneycondition = moneycondition; 
    This.returnmoney = Returnmoney; 
  } 
 
  @Override public 
  Double Acceptcash (double) {//Multiple rebate 
    if (Money >= moneycondition) {returns Money 
      - Math.floor (money/moneycondition) * Returnmoney; 
    } else {return money 
      ; 
    } 
  } 
   
   
} 

/** * Executes the corresponding behavior according to the passed policy class * * public class Cashcontext {private Icashsuper casher; 
  Public Cashcontext () {} public Cashcontext (Icashsuper casher) {this.casher = Casher; 
  public void Setcasher (Icashsuper casher) {this.casher = Casher; 
  ///According to the specific policy object, the algorithm behavior that calls it is public double acceptcash (double) {return This.casher.acceptCash (money); } 
   
} 

public class Test {public 
  static void Main (string[] args) { 
    double = 998;//original Price 
    Cashcontext cashcontext = new Cashcontext (new Cashnormal ()); 
    System.out.println ("Original price:" + cashcontext.acceptcash (money)); The usual strategy 
     
    Cashcontext.setcasher (new Cashrebate (8.5)); 
    System.out.println ("Dozen 85 percent:" + cashcontext.acceptcash); Discount  Strategy  85 percent 
     
    Cashcontext.setcasher (new Cashreturn); 
    SYSTEM.OUT.PRINTLN ("Full 300:" + cashcontext.acceptcash (money)); Return policy  full 300 
     
  } 
} 

Print

Original Price: 998.0 
85 Percent: 848.3 
full 300 return 50:848 

The difference between a policy pattern and a state pattern
we have learned that the two schemas are very similar in structure, but they still have different places. Here's a look at some of the key differences between them.

    The
    • policy pattern encapsulates a series of related algorithms that allow clients to use different behaviors by combining and delegating at run time, while the state pattern allows objects to exhibit different behaviors in different states. Another difference between the two modes of
    • is that the state pattern encapsulates the state of the object, and the policy pattern encapsulates an algorithm or policy. Because the state is coupled to the object, it cannot be reused, and the policy or algorithm is independent of its context so that it can be reused. In the
    • state mode, the state itself contains a reference to the context in which the State migration is implemented, but the policy pattern does not have a reference to the message
    • the specific policy can be passed as a parameter to the object that uses them. For example, Collections.sort () accepts a comparator, which is a strategy. The other state itself is part of the context object that, over time, migrates from one State migration to another.
    • Although both modes follow the open and closed principle, the policy pattern follows a single responsibility principle, because each policy encapsulates a separate algorithm, and different policies are independent of other policies. Changing a policy does not affect the implementation of another policy.
    • Theoretically, there is a difference between the policy pattern and the state pattern, which defines an object "how" to do something, such as how to sort the data, and on the other hand, the state pattern defines "what" and "when", such as what an object can do, Which state it is in at a point in time. The migration order of the
    • state is defined in the state mode, which is not required by the policy pattern. The client is free to choose which policy to use. Examples of the common policy patterns of
    • are encapsulation algorithms, such as sorting algorithms, cryptographic algorithms, or compression algorithms. If you find that you need to use a different algorithm in your code, you can consider using a policy model. And if you need to manage states to migrate between States, rather than nesting many conditional statements, the state pattern is your first choice because it's very simple.
    • The last and most important difference of the
    • is that the policy pattern is handled by the client, and the change context or state object can take place.

This is all about the differences between the policy and state patterns in Java. As I said, they look very similar in a UML diagram, both of which follow the open and closed principle and encapsulate the behavior. A policy pattern is used to encapsulate an algorithm or policy that is supplied to a context object at run time as a parameter or as a composite object, while a state pattern is used to manage State migration.

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.