Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the structure of the Java policy pattern

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is the structure of the Java strategy model". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The policy pattern is the packaging of the algorithm, which separates the responsibility of using the algorithm from the algorithm itself and delegates it to different object management. The policy pattern usually wraps a series of algorithms into a series of policy classes as a subclass of an abstract policy class. In one sentence, it is: "prepare a set of algorithms and encapsulate each algorithm so that they can be interchangeable." The structure of the policy pattern instance is explained with a schematic implementation.

This model involves three roles:

● environment (Context) role: holds a reference to Strategy.

● Abstract Policy (Strategy) role: this is an abstract role, usually implemented by an interface or abstract class. This role gives the required interfaces for all specific policy classes.

● specific Policy (ConcreteStrategy) role: wraps the relevant algorithm or behavior.

source code

Environmental role class

Public class Context {/ / holds a specific policy object private Strategy strategy; / * constructor, passing a specific policy object * @ param strategy specific policy object * / public Context (Strategy strategy) {this.strategy = strategy } / * Policy method * / public void contextInterface () {strategy.strategyInterface ();}}

Abstract policy class

Public interface Strategy {/ * Policy method * / public void strategyInterface ();}

Specific policy class

Public class ConcreteStrategyA implements Strategy {@ Override public void strategyInterface () {/ / related business}} public class ConcreteStrategyB implements Strategy {@ Override public void strategyInterface () {/ / related business}} public class ConcreteStrategyC implements Strategy {@ Override public void strategyInterface () {/ / related business}} usage scenario

Suppose you want to design a shopping cart system for an e-commerce website that sells all kinds of books. One of the simplest cases is to multiply the unit price of all the goods by the quantity, but the actual situation is certainly more complicated than that. For example, this website may offer a 20% discount per copy for all senior members, 10% discount per copy for intermediate members, and no discount for junior members.

According to the description, the discount is based on one of the following algorithms:

Algorithm one: there is no discount for junior members.

Algorithm 2: offer 10% promotion discount to intermediate members.

Algorithm 3: offer 20% promotional discount to senior members.

The structure diagram implemented using the policy pattern is as follows:

source code

Abstract discount class

Public interface MemberStrategy {/ * calculate the price of the book * @ param booksPrice the original price of the book * @ return calculate the discounted price * / public double calcPrice (double booksPrice);}

Discount category for junior members

Public class PrimaryMemberStrategy implements MemberStrategy {@ Override public double calcPrice (double booksPrice) {System.out.println ("No discount for junior members"); return booksPrice;}}

Discount category for intermediate members

Public class IntermediateMemberStrategy implements MemberStrategy {@ Override public double calcPrice (double booksPrice) {System.out.println ("10% discount for intermediate members"); return booksPrice * 0.9;}}

Advanced member discount category

Public class AdvancedMemberStrategy implements MemberStrategy {@ Override public double calcPrice (double booksPrice) {System.out.println ("20% discount for premium members"); return booksPrice * 0.8;}}

Price category

Public class Price {/ / holds a specific policy object private MemberStrategy strategy; / * constructor, passing in a specific policy object * @ param strategy specific policy object * / public Price (MemberStrategy strategy) {this.strategy = strategy } / * calculate the price of the book * @ param booksPrice the original price of the book * @ return calculate the discounted price * / public double quote (double booksPrice) {return this.strategy.calcPrice (booksPrice);}}

Client

Public class Client {public static void main (String [] args) {/ / Select and create the policy object MemberStrategy strategy = new AdvancedMemberStrategy (); / / create environment Price price = new Price (strategy); / / calculate the price double quote = price.quote (300); System.out.println ("the final price of the book is" + quote);}}

As can be seen from the above example, the policy mode only encapsulates the algorithm, provides a way for the new algorithm to be inserted into the existing system, and the old algorithm "retires" from the system, and the policy pattern does not determine when and which algorithm to use. It is up to the client to decide which algorithm to use under what circumstances.

Cognitive strategy model

The focus of the strategy model

The focus of the strategy pattern is not how to implement the algorithms, but how to organize and invoke these algorithms, so as to make the program structure more flexible, better maintainability and expansibility.

Equality of algorithm

One of the most important characteristics of the strategy pattern is the equality of each strategy algorithm. For a series of specific strategy algorithms, everyone's status is exactly the same, and it is precisely because of this equality that algorithms can be replaced with each other. All the strategy algorithms are independent and independent of each other in implementation.

So this series of policy algorithms can be described as follows: policy algorithms are different implementations of the same behavior.

Uniqueness of run-time policies

During the run, the policy pattern can only use one specific policy implementation object at a time, although it can be dynamically switched between different policy implementations, but only one can be used at the same time.

A public act.

It is common to see that all specific policy classes have some public behavior. At this point, you should put these public behaviors into the common abstract policy role Strategy class. Of course, at this point, the abstract policy role must be implemented using the Java abstract class, not the interface.

This is also a typical standard practice of centralizing code above the inheritance hierarchy.

Advantages of the policy model

(1) the strategy model provides a way to manage related algorithm families. The hierarchical structure of a policy class defines an algorithm or behavior family. Proper use of inheritance can move common code into the parent class, thus avoiding code duplication.

(2) multiple conditional (if-else) statements can be avoided by using policy mode. Multiple conditional statements are not easy to maintain. it mixes the logic of which algorithm or behavior to take with the logic of the algorithm or behavior, all listed in a multiple conditional statement, which is more primitive and backward than the method of inheritance.

Shortcomings of the policy model

(1) the client must know all the policy classes and decide which one to use. This means that the client must understand the differences between these algorithms in order to select the appropriate algorithm class at the right time. In other words, the policy pattern applies only if the client knows the algorithm or behavior.

(2) because the policy pattern encapsulates each specific policy implementation into a class separately, if there are many alternative policies, then the number of objects will be considerable.

This is the end of the content of "what is the structure of the Java strategy model". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report