Let's first imagine a scenario: plug a bunch of algorithms into the same piece of code. , and then use if - else and switch - case to determine which algorithm to use.
For example: Form validation, the data itself may be nsstring , nsinteger,nsfloat ... Sometimes it is not only to verify the type but also to verify the length, or there are other validations ... If you use if, sometimes it feels like a nightmare. Wake up, add a strategy mode. Wow, the world suddenly became very beautiful.
What is the policy mode:
The official definition: Define a series of algorithms, encapsulate them one after another, and they can replace each other. This pattern allows the algorithm to exist independently of the client that uses it.
Directly on the example:
There is one customtextfield that needs to be validated, then there is a inputvalidator( the base class for validation ) and a series of subclasses of validation, Alphainputvalidator,numericinputvalidator ...
1. inside your controller, the entrance is called directly:
[(customtextfield*)TextFieldValidate];
2. Customtextfield implementation class:
@implementationCustomtextfield
@synthesizeinputvalidator=inputvalidator_;
- (BOOL)Validate {
nserror*error =nil;
BOOLvalidationresult =[inputvalidator_ validateinput: Self error:&error];
if (!validationresult) {
uialertview*alertview =[[Uialertview alloc]initwithtitle:[ Error Localizeddescription]
message:[error Localizedfailurereason]
Delegate: Nil
Cancelbuttontitle: nslocalizedstring (@ "OK"@ "")
Otherbuttontitles: Nil ];
[AlertviewShow];
[Alertviewrelease];
}
returnvalidationresult;
}
@end
@implementationinputvalidator
A stubfor any actualvalidation strategy
- (BOOL)validateinput:(uitextfield*)input Error:(nserror*) error {
if (error) {
*error= nil;
}
returnNO;
}
Then write the relevant implementation in Alphainputvalidator, Numericinputvalidator .
OK, now I know a little bit about the strategy model. We'll take a look.
When to use Policy mode:
1. A class uses multiple conditional statements to define many behaviors in its operations. We can move the conditional branches into their own policy classes.
2. Various variants of the algorithm are required.
3. It is necessary to avoid exposing complex, algorithmic-related data structures to clients.
Programming-Policy Mode