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