Java design mode-policy mode

Source: Internet
Author: User

When dealing with the same type of problem, different processing logic is often used according to different situations. For example, according to user choice to determine which payment method the user uses, for the user to choose the payment method, the program will automatically invoke the processing logic.

It is often our practice to use switch or if...else in a class to make conditional judgments. Of course we can do this when there are fewer branches to deal with. But when we need to extend it or maintain it, we will encounter other places when the class becomes large or maintained. In fact, this is because the design class does not follow the object-oriented principle of low-coupling high cohesion.

We can choose the strategy mode and abstract the common operation as an interface. Our core calling class just needs to get the implementation class of the interface and invoke the Operation method. In this way, the core calling class does not care about which instance the specific call is, which is the equivalent of uniform processing.

Please refer to the policy model to simulate the shopping payment example. Source code reference: Https://github.com/sgyyz/java-pattern-demo.


later, more Java design patterns are better demonstrated through real-world examples, allowing more people to understand design patterns and apply them to their own real-world development. If there is something wrong, please point out, we discuss together.

This article is from the "Sg-yyz" blog, make sure to keep this source http://sgyyz.blog.51cto.com/5069360/1547624

Java design mode-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.