In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to completely eliminate multiple, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Post a specification from Ali's Java Development Manual first.
Let's not explore other ways, but mainly talk about the strategic model.
Define
Policy pattern (Strategy Design Pattern): encapsulates interchangeable behaviors and uses delegates to decide which one to use.
A strategy pattern is a behavioral design pattern that allows you to define a series of algorithms and put each algorithm into a separate class so that the objects of the algorithm can replace each other.
At run time, I send you different "key" for this class of methods, and your method executes different business logic.
You taste, you taste carefully, isn't that what if else does?
First take an intuitive look at the traditional multiple if else code
Public String getCheckResult (String type) {if ("check 1" .equals (type)) {return "execute business logic 1";} else if ("check 2" .equals (type)) {return "execute business logic 2";} else if ("check 3" .equals (type)) {return "execute business logic 3" } else if ("check 4" .equals (type)) {return "execute business logic 4";} else if ("check 5" .equals (type)) {return "execute business logic 5";} else if ("check 6" .equals (type)) {return "execute business logic 6";} else if ("check 7" .equals (type)) {return "execute business logic 7" } else if ("check 8" .equals (type)) {return "execute business logic 8";} else if ("check 9" .equals (type)) {return "execute business logic 9";} return "does not return a business error in the processed logic";}
Look at it this way, if you still think it's clear, imagine all kinds of complex business logic methods in these return.
Of course, the role of the policy pattern is not only to avoid lengthy if-else or switch branches, but also to provide framework extension points like the template method pattern.
There are many examples on the Internet, such as the planning of different routes and the choice of different payment methods are all typical if-else problems, as well as typical strategy mode problems. Chestnut we will look at it later, first look at the class diagram of the strategy pattern, and then transform multiple judgments.
Class diagram
The policy model involves three roles:
Strategy: policy interface or policy abstract class that constrains a series of policy algorithms (Context uses this interface to invoke specific policy implementation algorithms)
ConcreateStrategy: concrete policy class (implementing policy interface or inheriting abstract policy class)
Context: context class that holds instances of specific policy classes and is responsible for invoking related algorithms
The idea of applying strategy model to solve the problem
Example
Let's take a look at the simplest policy mode, demo:
1. Policy API (define policy)
Public interface Strategy {void operate ();}
2. Implementation of the algorithm.
Public class ConcreteStrategyA implements Strategy {@ Override public void operate () {/ / specific algorithm to implement System.out.println ("execute business logic A");}} public class ConcreteStrategyB implements Strategy {@ Override public void operate () {/ / specific algorithm to implement System.out.println ("execute business logic B");}}
3. The realization of context
Public class Context {/ / holds a specific policy object private Strategy strategy; / / constructor, passing in the specific policy object public Context (Strategy strategy) {this.strategy = strategy;} public void doSomething () {/ / call the specific policy object to operate strategy.operate ();}}
4. Client use (use of policies)
Public static void main (String [] args) {Context context = new Context (new ConcreteStrategyA ()); context.doSomething ();}
Ps: the way this strategy is used is actually very rigid, and it's no different from writing a lot of if-else when you actually use it, so we usually combine factory classes to dynamically determine which strategy to use at run time. The policy model focuses on how to select the policy, and the factory model focuses on how to create the policy.
Parsing strategy model
The function of the strategy pattern is to separate the specific algorithms from the specific business processing, implement them into separate algorithm classes, and form a series of algorithms, so that these algorithms can replace each other.
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.
In fact, the specific function of each strategy algorithm is the original concrete implementation in the if-else structure, and each if-else statement is an equal functional structure, which can be said to be brotherly relationship.
The policy pattern encapsulates the specific implementation of each equality into a separate policy implementation class, and then interacts with the specific policy class through the context.
"Policy pattern = logical dispatch of each policy class + context that implements the policy interface (or abstract class)"
The essence of Strategy pattern: separation algorithm, Choice and implementation-- "Grinding Design pattern"
So, the policy pattern is only an adjustment in the code structure, even if the policy pattern is used, there is not a logic that should be written, and when it comes to logic dispatch, it is just a disguised if-else.
Its optimization point is that it abstracts out the interface, encapsulates the business logic into an implementation class, and replaces it arbitrarily. It is easier to maintain and extend than direct if-else in complex scenarios (with more business logic).
Who will choose the specific strategy algorithm?
If you handwrite the demo above, you will find that it is not as easy as if-else, especially when judging logic, each logic has to construct a context object, which is laborious.
In fact, in the policy mode, we can define who chooses the specific policy algorithm, there are two kinds:
Client: when using the context, it is chosen by the client, like the demo above
Context: the client does not need to select, the specific policy algorithm is selected by the context, which can be specified in the constructor
Advantages and disadvantages
Advantages:
Avoid multiple conditional statements: that is, avoid a lot of if-else
Better scalability (fully in line with the open-closed principle): it is easy to extend the new policy implementation in the policy pattern, without modifying the context, just add a new policy implementation class
Disadvantages:
Customers must understand the difference of each strategy (this can be solved through IOC, dependency injection)
The number of objects has been increased: each specific policy is encapsulated into a class, and there may be many alternative policies.
Only suitable for flat algorithm structure: a series of algorithms in policy mode are equal, that is, only one algorithm is used at run time, which limits the level of algorithm use and cannot be used in nesting.
Thinking
In practical use, it is often not just the application of a single design pattern, it is generally mixed, and the combination of patterns is not set, so it is necessary to analyze specific problems.
Policy patterns are often used in conjunction with other patterns, such as factories, templates, etc., which need to be combined with their own business.
Remember, don't force patterns to use design patterns, and don't complicate simple problems.
The strategy mode is not designed to eliminate if-else, so don't equate it with if-else. It embodies the principle of "closed to modification and open to extension".
This is not to say that when you see an if-else, you want to optimize it with a strategy pattern. The business logic is simple, and you don't have to rigidly design patterns in scenarios that can be solved with a few enumerations or defender sentences.
Application of Policy pattern in JDK
In JDK, the Comparator comparator is a policy interface, and our commonly used compare () method is a concrete policy implementation that defines collations.
Public interface Comparator {int compare (T1, T2); / /. }
When we want to customize the collation, we can implement Comparator.
At this point we rewrite the compare () method in the interface, which is the specific policy class (although this may be the inner class). When we call the sorting method sort () of Arrays, we can use either the default collation or custom rules.
Public static void main (String [] args) {Integer [] data = {4 Integer [] args) {@ Override public int compare (Integer o1, Integer O2) {if (o1 > O2) {return 1;} else {return-1;}}; Arrays.sort (data,comparator); System.out.println (Arrays.toString (data));}
The sort () method of Arrays, which sorts according to its own method if there are custom rules, otherwise goes to the source logic.
Public static void sort (T [] a, Comparator
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.