Policy mode: the interface object that encapsulates the behavior interface, implements the algorithm family, and puts the behavior in the superclass, and sets the behavior object in the sub-class.
The principle is: separate the change part, the encapsulation interface, based on the interface programming various functions.
Why Use Policy mode
{
problems with inheritance: (for policy mode)
Local changes to the class, especially the changes in the superclass, can affect other parts, which can have spillover effects.
Overflow effect:
A function (method) has been added to the superclass, and the subclass inherits this method directly.
Super class inside Dug a pit, each sub-class to fill, increase the workload, the complexity is n squared,
}
Under what circumstances is policy mode used?
My understanding: There are many kinds of shapes or functions in the case. And each of its shapes or functions behaves differently at different times. That is, when you hear something, the performance is not the same.
For example: fish can swim, but some fish is slowly swim, some fish swim in general, some fish swim quickly. So you can define an interface iswim, and then just use Slowswim,generalswim, Quickswim three classes to implement this Iswim interface respectively. Slowswim,generalswim,quickswim these three classes are called behavior families.
How to use this strategy mode?
Or, according to the fish above, define an abstract fish class, in which fish has a iswim field, which is passed through the construction method.
Now there's a fake with a whale is fast-swimming
Public classWhaleextendsfish{{Privateiswim Swim; Whale (Iswim swim) { This. swim=swim; } Public voidswim () {swim.swim (); } Public void StaticMain (string[] arg) {//whales are very fast-swimming, so the sub-class of the incoming Iswim quictswimWhale whale=NewWhale (NewQuictswim ());
Whale.swim (); }}
What are the advantages of the strategy model?
1, when we want to add a behavior (method) can not change the source code, directly add a class can be.
2, after we have defined all the actors, we must combine them with our own conduct.
What are the disadvantages of the strategy model?
1, the client must know that all the policy classes are the behavioral family and decide which policy class to use at its own discretion. This means that the client must understand the differences between these algorithms in order to select the appropriate algorithm classes at the right time. In other words, the policy pattern applies only to situations where the client knows all the algorithms or behaviors.
2, there are many classes of behavioral families.
Java design mode 1-policy mode