In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to realize the strategy mode of Java with code". In the daily operation, I believe that many people have doubts about how to realize the strategy mode of Java with code. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to realize the strategy mode of Java with code". Next, please follow the editor to study!
Strategy mode
Policy pattern is one of the 23 design patterns in Java, so let's take a look at what a policy pattern is.
1. What is the policy model
Definition of policy pattern:
The pattern defines a series of algorithms and encapsulates each algorithm so that they can replace each other, and the changes in the algorithm will not affect the customers who use the algorithm. The policy pattern belongs to the object behavior pattern, which encapsulates the algorithm, separates the responsibility of using the algorithm from the implementation of the algorithm, and delegates to different objects to manage these algorithms.
In fact, in real life, we often encounter situations where there are a variety of strategies to choose from to achieve a certain goal, for example, travel by plane, train, bike or drive your own car and so on. Or, for example, online shopping, you can choose Industrial and Commercial Bank of China, Agricultural Bank, Construction Bank and so on, but they all provide the same algorithm, that is, to help you pay.
A similar situation will be encountered in software development. when there are multiple algorithms or strategies to achieve a function, we can choose different algorithms or strategies according to different environments or conditions to complete the function.
2. the advantages and disadvantages of the strategy model.
Advantages:
Multiple conditional statements are not easy to maintain, but using policy mode can avoid using multiple conditional statements.
A series of reusable algorithm families are provided. Proper use of inheritance can transfer the common code of the algorithm family to the parent class, thus avoiding repetitive code.
Provide different implementations of the same behavior, and customers can choose different ones according to different time or space requirements
It provides perfect support for the opening and closing principle, and can flexibly add a new algorithm to the algorithm without modifying the original code.
The implementation of the algorithm is moved to the concrete policy class, and the separation of the two is realized.
Disadvantages:
The client must understand the differences between all policy algorithms in order to select the appropriate algorithm class at the right time.
Policy patterns cause a lot of policy classes, making it more difficult to maintain
3. The structure of the policy model.
1. Abstract policy class: defines a common interface, which is implemented by different algorithms in different ways. Environment roles use this interface to call different algorithms, generally using interfaces or abstract classes.
two。 Specific policy class: implements the interface of abstract policy definition and provides specific algorithm implementation.
3. Environment class: holds a reference to a policy class and finally calls it to the client.
Structure diagram:
4. Code implementation
Now there are three ducks: green duck, red duck and duckling (ducklings can't fly yet)
Now define a parent class of a duck: there are methods that can call, and ways to display the appearance (because each one is different, it needs to be overridden by subclasses)
Can also fly (policy mode is used here)
Public abstract class duck {/ / Ducks will call: public void quack () {System.out.println ("quack");} / / the appearance of ducks is different, so the subclass implements public abstract void display (); / / the following policy pattern is used: / / hold the interface in the parent class, and the interface replaces the flight behavior (combination) private Flying flying. / / provide set method public void setFlying (Flying flying) {this.flying = flying;} public void fly () {flying.Fly ();}}
Define a flight interface:
/ * Policy API: realizes the flight behavior of ducks * / public interface Flying {void Fly ();}
We know that the strategy pattern is to encapsulate the algorithms that need to be used, and encapsulate two methods that can fly and can't fly in another package:
Can fly (inherit to the above flight interface, rewrite the flight method):
Public class FlyWithWin implements Flying {@ Override public void Fly () {System.out.println (I can fly);}}
Can't fly:
Public class FlyNoWay implements Flying {@ Override public void Fly () {System.out.println ("I can't fly");}
Note: the above two methods are encapsulated separately as an algorithm family, and then when the program needs to use one of the algorithms, the program will not be affected by the algorithm change, because the final effect of the algorithm is the same.
Red-haired ducks
/ * Red duck * / public class RedDuck extends duck {public RedDuck () {super (); / / inject the duck with the ability to fly, here is through the flying algorithm super.setFlying (new FlyWithWin ()) in the algorithm family;} @ Override public void display () {System.out.println ("I am the red duck");}}
Mallard duck:
/ * * Green duck * / public class GreenDuck extends duck {public GreenDuck () {super (); / / inject the duck with the ability to fly, which is also through the flying algorithm super.setFlying (new FlyWithWin ()) in the algorithm family;} @ Override public void display () {System.out.println ("I am the green duck");}}
Ducklings (can't fly):
/ * ducklings can't fly yet * / public class SamllDuck extends duck {public SamllDuck () {super (); / / ducklings can't fly, so they use super.setFlying (new FlyNoWay ()), an algorithm that can't fly in the algorithm family;} @ Override public void display () {System.out.println ("I'm still a duckling"). } / / because the call of a duckling is different from that of a big duck, the method of rewriting the call public void quack () {System.out.println ("quack");}}
Test class:
Public class Test {public static void main (String [] args) {System.out.println ("* Test Duck Program *"); duck d = null; / / this is to take turns running! D = new RedDuck (); / / Test the red duck d = new GreenDuck (); / / Test the green duck d = new SamllDuck (); / / Test the duckling d.display (); d.quack (); d.fly (); System.out.println ("* Test completed * *");}}
When using a red duck as an object:
* Test Duck Program *
I'm the red duck.
Quack
I can fly
* * Test completed * *
When using a green duck as an object:
* Test Duck Program * I am a green duck quack and I can fly * * Test completed *
When using ducklings as objects:
* Test Duck Program *
I'm still a duckling.
Quack ~ quack
I can't fly.
* * Test completed * *
5. The application scenario of policy mode.
1. When a system needs to dynamically select one of several algorithms, each algorithm can be encapsulated into a policy class.
two。 A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class, and each conditional branch can be moved into its own policy class to replace these conditional statements.
3. When the algorithms in the system are completely independent of each other and are required to hide the implementation details of the specific algorithm from the customer
4. When the system requires that customers who use the algorithm should not know the data they operate on, they can use the policy pattern to hide the data structure related to the algorithm.
5. Multiple classes differ only in showing different behaviors. You can use policy patterns to dynamically select specific behaviors to be executed at run time.
At this point, the study on "how to implement the strategy mode of Java in code" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.