The policy pattern can be considered as "pluggable algorithm (pluggable)", separating the behavior of subclasses from the common logic, and abstracting the behavior of subclasses into common logic, so that the behavior of substituting subclasses does not affect the public logic, nor does it affect the logic of the calling class.
The following is a simple example of a strategy pattern, as shown in the following class diagram:
The code for the public logic context is as follows:
Public classcontext{ Public voidContextinterface () {//Add common code hereStrategy.strategyinterface (); //Add common code here } /** * @linkAggregation * @directed*/ Privatestrategy strategy; Private voidSetstrategy (Strategy strategy) { This. Strategy =strategy; } PrivateStrategy Getstrategy () {return This. Strategy; }}
The interface of the sub-class algorithm is as follows:
Abstract Public class strategy{ publicabstractvoid strategyinterface ();}
The specific algorithm is as follows:
Public class extends strategy{ publicvoid strategyinterface () { //write you Algorithm codehere }}
When we want to modify the implementation of the specific algorithm, we just rewrite a class, inherit the strategy interface, the public logic in the context does not need to be modified.
Examples of policy patterns in Java:
The environment role is played by container, the algorithm interface is played by LayoutManager, and the concrete algorithm is played by GridBagLayout, GridLayout and so on.
Policy mode (strategy method)