What is a policy mode?
Strategy pattern is mainly about using different algorithm at different situation.
The rule mode, also known as the algorithm cluster mode, defines different algorithm families and can be replaced with each other. This mode allows algorithm changes to be independent of algorithm customers.
The advantage of the Policy mode is that you can dynamically change the behavior of objects.
Generally, the policy mode is divided into the following three roles:
1. Context: Hold a policy reference
2. abstract strategy: defines public interfaces for multiple specific policies. Different algorithms in a specific policy class implement this interface in different ways; context uses these interfaces to call different implemented algorithms. Generally, we use interfaces or abstract classes.
3. concretestrategy: Implements related algorithms or operations in the abstract policy class.
/*** The policy mode first defines an interface behavior, implements different behavior implementations for the interface subclass, and then maintains a reference pointing to the interface class in another scenario class. In this way, different * behavior algorithms are called in different scenarios to process */interface Strategy {// define the interface method public void processprice (INT price );} // VIP treatment class VIP implements Strategy {public void processprice (INT price) {system. out. println ("VIP with" + Price + "Yuan sitting in VIP room"); }}// general treatment Class ordinary implements Strategy {public void processprice (INT price) {system. out. println ("ordinary with" + Price + "");} class situation {private strategy Strategy; public situation (strategy Strategy) {This. strategy = strategy;} public void handconsumer (INT price) {This. strategy. processprice (price) ;}} public class main {public static void main (string [] ARGs) {ordinary ord = new ordinary (); VIP = new VIP (); situation S1 = new situation (ORD); situation S2 = new situation (VIP); s1.handconsumer (10); s2.handconsumer (10 );}}
Design Pattern policy pattern