Rule mode definition
Policy patterns define a series of algorithms, encapsulate each algorithm, and make them replaceable. The rule mode allows algorithms to change independently of customers who use it. Put a typical class diagram first:
In the figure, algorithminterface () is a so-called algorithm. All strategya, B, and C are encapsulated and implemented. The yellow part is called!
In my project experience, I will illustrate the policy mode with examples.
Rule Mode
Project software login process. There are first logon, second logon, and SMS logon. There are some differences between the three logon methods. First, let's talk about the same place, for example:
1. Before Logon: connect to the server, regardless of the method you need to connect to the server. Method Name connectserver ();
2. Logon: password encryption algorithm. Method Name: encryptpwd ();
3. Some logical operations are available after logon. Method Name: dealwithloninok ();
However, password operations are different in the logon process, and some logical operations are different after logon. According to the general thinking: we must add a switch in encryptpwd to distinguish the logic of different types of logon.
The method for using the Policy mode is as follows: first define a base class loginstrategy and define the above three interfaces.
@ Interface ftloginstrategy: nsobject {}-(void) connectserver;-(void) encryptped :( nsstring *) PWD;-(void) dealwithloginok;-(nsstring *) loginstrategytype; // used to differentiate logon types. The base class returns const string and @ end
Three classes are derived from loginstrategy: firstloginstrategy, secondloginstrategy, and smsloginstrategy.
Regardless of the login method, it is connected to the same server. Therefore, the logic of connectserver () is the same, so the derived class does not implement connectserver (). However, three Derived classes need to be implemented.
-(void) EncryptPWD;-(void) DealwithLoginOK;
Therefore, you can use this method according to different requirements when calling Logon:
Loginstrategy * login = [[firstloginstrategy alloc] init]; // loginstrategy * login = [[secondloginstrategy alloc] init]; /// // loginstrategy * login = [[smsloginstrategy alloc] init]; // or [Login connectserver]; [Login encryptpwd :( PWD)]; [Login dealwithloginok];
Benefits of Rule Mode
I have seen that many of the statements in the Policy mode are good, but the examples are not very easy to understand. This time, I will write out the real cases in the project.
The advantage is obvious: If you need to add a QR code to log on in the future, you can add another class based on the three types of Logon codes.
The policy mode is still the application of the object-oriented ideology "inheritance + polymorphism + encapsulation". The design mode can be used to distinguish between types, but the design mode makes the code more elegant.