The policy (strategy) pattern defines a series of algorithms, encapsulates each algorithm, and allows them to be replaced with each other. The policy pattern makes the algorithm independent of the customers who use it. The strategy pattern is the wrapper over the algorithm, which separates the responsibility of the algorithm and the algorithm itself, delegating to different object management. When you see the strategy mode sometimes compared with the simple factory, there is a lot of confusion, are inherited polymorphism feel not much difference, simple Factory mode is the management of objects, strategy mode is the encapsulation of behavior. You can take a simple look at the structure diagram first:
Before simple factory is through the bank card as an example of the simple factory will be different bank cards abstracted out, if in the strategy mode we can be each bank card shopping, eating, housing. Abstract as a simple consumption strategy, you can also use the operating system analogy, Windows,os X,linux can be used as a simple object abstraction, the system is the default software, we do not need to tube software installation, if there is no software, we need to download, The installation of the software can be packaged as a policy.
Abstract class of strategy:
@interface softwarestrategy:nsobject-(void) installstrategy; @end
The policy class that inherits strategy's Xcode:
@implementation xcodestrategy-(void) installstrategy{ NSLog (@ "Xcode installation succeeded");} @end
The strategy class of QQ that inherits strategy:
@implementation qqstrategy-(void) installstrategy{ NSLog (@ "QQ installation Success"); NSLog (@ "Original address: Http://www.cnblogs.com/xiaofeixiang");} @end
Context class:
typedef ns_options (Nsinteger, Strategytype) { strategyxcode, strategyqq}; @interface Softwarecontext: nsobject-(Instancetype) Initwithstrategytype: (strategytype) strategytype;-(void) Installresult; @end
Implementation of the context:
@interface softwarecontext () @property (strong,nonatomic) softwarestrategy *strategy; @end @implementation softwarecontext-(Instancetype) Initwithstrategytype: (strategytype) strategytype{ self=[super init]; if (self) { switch (strategytype) {case Strategyxcode: self.strategy=[[xcodestrategy alloc]init]; break; Case STRATEGYQQ: self.strategy=[[qqstrategy alloc]init]; break; } } return self;} -(void) installresult{ [Self.strategy installstrategy];} @end
Final Call:
Softwarecontext *context=[[softwarecontext Alloc]initwithstrategytype:strategyxcode]; [Context Installresult];
Here are three concepts to look at more clearly:
Environment (context) Role: holds a reference to a strategy;
Abstract policy (Strategy) role: This is an abstract role, usually implemented by an interface or abstract class. This role gives the interface required for all the specific policy classes;
specific strategy (concretestrategy) Role: wrapping the relevant algorithm or behavior;
iOS Development-Strategy mode