Strategy Basic Concepts
Policy mode (strategy pattern):
- Define a set of algorithms that encapsulate each algorithm and are interchangeable between them.
- Using object-oriented inheritance and polymorphic mechanism implementation
Strategy in the
role:
- Context Wrapper role :
It is called the context role, the packaging function of the connecting link, shielding The high-level module to the policy, the direct access to the algorithm, packaging possible changes .
- Strategy Abstract policy roles :
Policy, an abstraction of an algorithm family, usually an interface that defines the algorithms and attributes that each policy or algorithm must have.
- Concrete Strategy specific policy roles :
Implement operations in an abstract policy, including specific algorithms
Understanding the Strategy model
- Advantages :
- The algorithm can be freely switched , because the implementation of the specific class will not affect the use of the interface, the interface does not modify the premise that the specific class can be freely switched ( polymorphic )
- Avoid multiple conditional judgments , which are determined by other modules, and the policy family only provides interfaces
- Good extensibility , can directly inherit the common interface to achieve polymorphism to expand, do not need to modify the existing classes
- Disadvantages :
- The number of policy classes is large (decorative mode can be used to prevent the explosion of the number of classes )
- All policy classes are exposed to external
Strategy's characteristics determine its application scenarios where the algorithm requires
Free SwitchingThe need
Masking Algorithm Rulesof the scene. Example strategy
Again, according to the scene to write code, the sense of the application of the strategy mode is too many .... and often we don't realize it when we use it ... Then the crap ends.
For example, as an editor, we want to color a piece of code to highlight it, then we will abstract the role of the brush, and then start our coloring tour ...
/** * Created by Liulin on 16-5-6. * * interface strategy{ voidOperate ();} class redpaint implements strategy{@Override Public voidOperate () {SYSTEM.OUT.PRINTLN ("Paint the Code to red!"); }} class bluepaint implements strategy{@Override Public voidOperate () {SYSTEM.OUT.PRINTLN ("Paint The code to blue!"); }} class Context{ PrivateStrategy strategy; PublicContext (Strategy strategy) { This. strategy = strategy; } Public voidOperate () {strategy.operate (); }} Public class strategytest { Public Static voidMain (String [] args) {Context context =NewContext (NewBluepaint ()); Context.operate (); Context =NewContext (NewRedpaint ()); Context.operate (); }}
The output results are as follows:
Spring extension
There are two kinds of proxy methods for the JDK and cglib when spring takes dynamic agent, which is implemented by the strategy mode.
Java design Pattern (ix) strategy (strategy) mode and spring extension