The strategy pattern is a common software design pattern, here is a simple introduction to the strategy model and the simple implementation of iOS.
The so-called strategy model, as the name implies is to adopt a different strategy. In general, in different situations, the method of dealing with a problem is not the same. For example, the sorting of strings and the sorting of numbers, although using a fast row, it is obviously impossible to use a piece of common code. Some people say that the CompareTo in Java can be done, but if you consider a problem: the same is the trip, the elderly frail, need a lot of rest, and the child is energetic, want to play more attractions. How to express the above information in the same mode and encapsulate it in a reasonable design pattern rather than rewriting similar code in large quantities requires learning and adopting a policy model.
Example
This example mainly uses the strategy pattern to determine whether Uitextfield satisfies the input requirements, such as the input can only be a number, if only the number is not prompted, if there are other characters are prompted error. Verify that the letters are the same.
First, we first define an abstract policy class iputvalidator. The code is as follows:
InputValidator.h
Copy Code code as follows:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
Static NSString * Const Inputvalidationerrordomain = @ "Inputvalidationerrordomain";
@interface Inputvalidator:nsobject
Stub method of the actual validation policy
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error;
@end
Inputvalidator.m
Copy Code code as follows:
#import "InputValidator.h"
@implementation Inputvalidator
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error
{
if (Error) {
*error = nil;
}
return NO;
}
@end
This is a policy base class, and then we're going to create two subclasses Numericinputvalidator and Alphainputvalidator. The specific code is as follows:
NumericIputValidator.h
Copy Code code as follows:
#import "InputValidator.h"
@interface Numericinputvalidator:inputvalidator
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error;
@end
Numericiputvalidator.m
Copy Code code as follows:
#import "NumericInputValidator.h"
@implementation Numericinputvalidator
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error
{
Nserror *regerror = nil;
Use the configured Nsregularexpression object to check the number of occurrences of the numeric type in the text box.
^[0-9]*$: Meaning that from the beginning of the line (expressed as ^) to the end (expressed as $) there should be 0 or more characters in the set of numbers (labeled [0-9]) (represented as *)
Nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@ "^[0-9]*$" options: Nsregularexpressionanchorsmatchlines error:®error];
Nsuinteger numberofmatches = [regex numberofmatchesinstring:[input text] options:nsmatchinganchored Range:NSMakeRange (0, [[input text] length])];
If there is no match, the error and no are returned
if (numberofmatches==0) {
if (Error!= nil) {
NSString *description = nslocalizedstring (@ "Input Validation faild", @ "");
NSString *reason = nslocalizedstring (@ "The input can contain only numerical values", @ "");
Nsarray *objarray = [Nsarray Arraywithobjects:description,reason, Nil];
Nsarray *keyarray = [Nsarray arraywithobjects:nslocalizeddescriptionkey,nslocalizedfailurereasonerrorkey, Nil];
Nsdictionary *userinfo = [nsdictionary dictionarywithobjects:objarray Forkeys:keyarray];
*error = [Nserror errorwithdomain:inputvalidationerrordomain code:1001 Userinfo:userinfo];
}
return NO;
}
return YES;
}
@end
AlphaInputValidator.h
Copy Code code as follows:
#import "InputValidator.h"
@interface Alphainputvalidator:inputvalidator
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error;
@end
Alphainputvalidator.m
Copy Code code as follows:
#import "AlphaInputValidator.h"
@implementation Alphainputvalidator
-(BOOL) ValidateInput: (Uitextfield *) input error: (NSERROR * *) error
{
Nserror *regerror = nil;
Use the configured Nsregularexpression object to check the number of occurrences of the numeric type in the text box.
^[0-9]*$: Meaning that from the beginning of the line (expressed as ^) to the end (expressed as $) there should be 0 or more characters in the set of numbers (labeled [0-9]) (represented as *)
Nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@ "^[a-za-z]*$" options: Nsregularexpressionanchorsmatchlines error:®error];
Nsuinteger numberofmatches = [regex numberofmatchesinstring:[input text] options:nsmatchinganchored Range:NSMakeRange (0, [[input text] length])];
If there is no match, the error and no are returned
if (numberofmatches==0) {
if (Error!= nil) {
NSString *description = nslocalizedstring (@ "Input Validation faild", @ "");
NSString *reason = nslocalizedstring (@ "The input can contain only letters", @ "");
Nsarray *objarray = [Nsarray Arraywithobjects:description,reason, Nil];
Nsarray *keyarray = [Nsarray arraywithobjects:nslocalizeddescriptionkey,nslocalizedfailurereasonerrorkey, Nil];
Nsdictionary *userinfo = [nsdictionary dictionarywithobjects:objarray Forkeys:keyarray];
*error = [Nserror errorwithdomain:inputvalidationerrordomain code:1002 Userinfo:userinfo];
}
return NO;
}
return YES;
}
@end
Both of them are inputvalidator subclasses. And then define a Customtextfield:
CustomTextField.h
Copy Code code as follows:
#import <UIKit/UIKit.h>
@class Inputvalidator;
@interface Customtextfield:uitextfield
@property (Nonatomic,strong) Inputvalidator *inputvalidator;
-(BOOL) validate;
@end
Customtextfield.m
Copy Code code as follows:
#import "CustomTextField.h"
#import "InputValidator.h"
@implementation Customtextfield
-(BOOL) Validate {
Nserror *error = nil;
BOOL Validationresult = [_inputvalidator validateinput:self error:&error];
if (!validationresult) {
Uialertview *alertview = [[Uialertview alloc] Initwithtitle:[error localizeddescription] Message:[error Localizedfailurereason] Delegate:nil cancelbuttontitle:nslocalizedstring (@ "OK", @ "") Otherbuttontitles:nil];
[Alertview show];
}
return validationresult;
}
@end
Finally, test whether the validation is complete in Viewcontroller
Viewcontroller.m
Copy Code code as follows:
#import "ViewController.h"
#import "CustomTextField.h"
#import "NumericInputValidator.h"
#import "AlphaInputValidator.h"
@interface Viewcontroller ()
@end
Copy Code code as follows:
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
_numbertextfield.inputvalidator = [Numericinputvalidator new];
_lettertextfield.inputvalidator = [Alphainputvalidator new];
Do no additional setup after loading the view, typically from a nib.
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any of the can is recreated.
}
#pragma mark-validbuttonmehtod
-(Ibaction) Validnumaction: (ID) Sender {
[_numbertextfield validate];
}
-(Ibaction) Validletteraction: (ID) Sender {
[_lettertextfield validate];
}
@end
The result: When we enter a condition that does not meet the conditions, it will display the message, and the condition will not have any hint.
Advantages
- A policy pattern is a way of defining a series of algorithms, conceptually, all of which are done in the same way, but with different implementations, it can invoke all the algorithms in the same manner, reducing the coupling between the various algorithmic classes and the use of algorithmic classes.
- The Stategy class hierarchy of the policy pattern defines some of the column's reusable algorithms or behaviors for the context. Inheritance helps to analyze the public functions in the extraction algorithm.
- The advantage of a policy pattern is that it simplifies unit testing because each algorithm has its own class that can be tested individually through its own interface.
Working with scenes
- A class uses multiple conditional statements in its operations to define many behaviors. We can move the relevant conditional branches to their own policy class
- Various variants of the algorithm are needed
- Need to avoid exposing complex, algorithmic-related data structures to clients
Summarize
summing up the implementation of the strategy approach is essentially the need to complete a thing (travel), but it is not clear what the need to use the strategy, so encapsulate a function to be able to take the required strategy (young OR old) as a parameter passed in, and use the appropriate strategy to complete the event processing.
Finally, a brief discussion of the individual's understanding of the mode of strategy and the idea of polymorphism in object-oriented first, polymorphism is a high-level, highly abstract concept, independent of language, is the essence of object-oriented thinking, and the strategy model is only a software design pattern, relatively more specific, and concrete implementation depends on the specific programming language, For example, OC and Java implementation method is not the same, is language-dependent. Second, polymorphism emphasizes that different objects invoke the same method with different results, and the policy pattern emphasizes that the same object (in fact, the object itself is not important) executes different methods in different situations, and that they are implemented in a highly similar way, That is, a method that shares the same parent class and overrides the parent class individually.
These views are purely personal, and you are welcome to correct and communicate with each other.