Design pattern of the Strategy mode (iOS development, code with OBJECTIVE-C show)

Source: Internet
Author: User

In the actual development process, the application needs are given by the product side, often he gives the first version of the function, we write the code, will be given the second version, the third edition of the function, and these features are in actual use, according to user needs and constantly increase. If, at the beginning of the code, we did not realize this, and did not prepare the code for subsequent additions, then there is no doubt that this project code will become more and more chaotic, resulting in such a loop:

      1. Product demand
      2. I write code on demand
      3. Product increase Demand
      4. In order to complete the task within the specified time, I add the code according to the need to increase the demand (due to the lack of thinking about the corresponding design, so that the code is long and messy)
      5. Product needs to grow again
      6. I added the code, because the previous code design is unreasonable, so that even if only a small function, I will add this code throughout the project all over the place
      7. Product feel a function is not good, to delete, and then I have to find in the project a variety of local functions of the code, delete, also have to go up and down the logical relationship
      8. This way, found that the workload is great, no time to read, no time to study, always the same quality code, skills can not be improved
      9. If not from their own body to find the reason, began to scold the product, something good always increase demand, think stay in this company boring, and then resign ...
      10. The next company, this cycle begins again ...

See a question and answer on the understanding:

Are programmers not feeling happy? Are you having a bad stay? Because no matter bat company or small and medium-sized companies, all kinds of overtime, daily code, no time to talk about girlfriends ....

See such a great answer: the technology is good, have a good, poor technology ...

    1. Now there is such a task, to do a shopping mall cashier software, the salesperson according to the customer's purchase of the product price and quantity, to the customer charges.

Very simple one needs a little analysis to get the interface:

Depending on the interface, you can also quickly write the main code:

#import <Foundation/Foundation.h> @interface Zytotalprices:nsobject@property (nonatomic, assign) double singleprices; @property (nonatomic, assign) int number;-(instancetype) initwithsingleprices: (NSString *) singleprices Number: (NSString *) number;-(double) totalprices; @end #import "ZYTotalPrices.h" @implementation zytotalprices-( Instancetype) Initwithsingleprices: (NSString *) singleprices number: (NSString *) number{    if (self = [super init]) {        Self.number = [number intvalue];        Self.singleprices = [Singleprices doublevalue];    }    return self;} -(double) totalprices{    return self.number * self.singleprices;} @end

Then the product comes running over and you say, now there are new needs, mall promotions, all merchandise hit 80 percent.

Think, directly in the-(double) Totalprices method inside, multiplied by 0.8 is OK ... This is to meet the existing needs, if one day the mall hit 70 percent or said, after the return of the original price, how to do?

2. Increase the discount

#import <Foundation/Foundation.h> @interface Zytotalprices:nsobject@property (nonatomic, assign) double Singleprices; A property string in the @property (nonatomic, assign) int number;/** * drop-down menu */@property (nonatomic, copy) NSString *itemstr ;-(Instancetype) Initwithsingleprices: (NSString *) singleprices number: (NSString *) number;-(double) totalprices; @end  #import "ZYTotalPrices.h" @interface zytotalprices ()/** * Discounted statement */@property (nonatomic, strong) Nsarray *discountstrs;/** * The specific value of the discount */@property (nonatomic, strong) nsarray *discountnumbers;/** * Discount corresponding subscript */@property (nonatomic, assign) int ind ex; @end @implementation zytotalprices-(Nsarray *) discountnumbers{if (!_discountnumbers) {_discountnumbers = @[    @ (1), @ (0.8), @ (0.5)]; } return _discountnumbers;}                -(Nsarray *) discountstrs{if (!_discountstrs) {_discountstrs = @[@ "normal charge", @ "hit 80 percent", @ "hit 50 percent"];    The default is normal charge self.index = 0; } return _discountstrs;} -(void) Setitemstr: (NSString *) itemstr{_itemsTR = [itemstr copy]; [Self.discountstrs enumerateobjectsusingblock:^ (NSString *obj, Nsuinteger idx, BOOL *stop)            {if ([obj isequaltostring:itemstr]) {self.index = (int) idx;        *stop = YES; }    }];}        -(Instancetype) Initwithsingleprices: (NSString *) singleprices number: (NSString *) number{if (self = [super init]) {        Self.number = [number intvalue];    Self.singleprices = [Singleprices doublevalue]; } return self;}    -(double) totalprices{double tempnumber = [Self.discountnumbers[self.index] doublevalue]; return Self.number * self.singleprices * tempnumber;} @end

The following interface is almost there: (Do not control it completely)

At this point, the product will need to increase the "300 get 100" activity. This is entirely possible to add one more method to the class to calculate this. However, this approach is not good, in fact,

We can completely pull out an abstract base class, there is a method in the base class, that is, to return the total amount of money, and the sub-classes of the different algorithms inherit from the base class, implement the method inside the base class, and then use the tool class according to different requirements to call different subclasses, so that the division of labor is very clear, if there Find this subclass increase on OK

3. Simple Factory mode

Note that, in fact, hit 80 percent, 70 percent, 60 percent ... Can be expressed entirely by a variable, there is no need to derive a lot of sub-categories, is a discount sub-class, the internal determination of the specific discount of the number of the same, the same as the full * * minus.

Object-oriented programming, the more classes the better, the division of classes is for encapsulation, but the basis of the partitioning class is abstract, the abstract collection of objects with the same properties and functions is the class.

How many folds, just the form of different, abstract analysis out, all the discount algorithm is the same, all discount algorithm should be a class. Similarly, the same is true of the full * * minus.

The code is as follows:

Abstract base classes: #import <Foundation/Foundation.h> @interface zytotalprices:nsobject@property (nonatomic, assign) double singleprices; @property (nonatomic, assign) int number;/** *  So, there is a method declaration in the abstract class that is given to the subclass * */-(double) totalprices; @end # Import "ZYTotalPrices.h" @implementation zytotalprices@end

Normal Price: #import "ZYTotalPrices.h" @interface zypricesnoraml:zytotalprices@end#import "ZYPricesNoraml.h" @ Implementation zypricesnoraml/** *  normal charge * */-(double) totalprices{    return self.singleprices * self.number;} @end

Discount: #import "ZYTotalPrices.h" @interface zypricesdiscount:zytotalprices/** *  discount rate for decimals */@property (nonatomic, Assign) Double moneyrebate;-(instancetype) Initwithmoneyrebate: (double) moneyrebate; @end #import "ZYPricesDiscount.h "@implementation zypricesdiscount-(Instancetype) Initwithmoneyrebate: (double) moneyrebate{    if (self = [super init ]) {        self.moneyrebate = moneyrebate;    }    return self;} -(double) totalprices{    return self.number * self.singleprices * self.moneyrebate;} @end

Rebate: #import "ZYTotalPrices.h" @interface zypricesreturn:zytotalprices/** *  Rebate conditions */@property (nonatomic, assign) Double moneycondition;/** *  Rebate Value */@property (nonatomic, assign) Double moneyreturn;-(instancetype) Initwithmoneycondition: (Double) moneycondition Moneyreturn: (double) moneyreturn; @end #import "ZYPricesReturn.h" @ Implementation zypricesreturn-(Instancetype) Initwithmoneycondition: (double) moneycondition MoneyReturn: (Double) moneyreturn{    if (self = [super init]) {        self.moneycondition = moneycondition;        Self.moneyreturn = Moneyreturn;    }    return self;} -(double) totalprices{    Double total = Self.number * self.singleprices;    Return total-(int) (total/self.moneycondition) * Self.moneyreturn;} @end

Tool class: #import <Foundation/Foundation.h> @class zytotalprices; @interface zypricestool:nsobject+ (Zytotalprices *) CREATETOTALPRICESWITHITEMSTR: (NSString *) itemstr; @end #import "ZYPricesTool.h" #import "ZYPricesNoraml.h" #import " ZYPricesDiscount.h "#import" ZYPricesReturn.h "static Nsarray *_arraystrs; @implementation zypricestool+ (Nsarray *)    arraystrs{if (_arraystrs = = nil) {_arraystrs = @[@ "normal charge", @ "full 300 return 100", @ "80 percent"]; } return _arraystrs;}        + (Zytotalprices *) Createtotalpriceswithitemstr: (NSString *) itemstr{[self arraystrs];        __block int index = 0; [_arraystrs enumerateobjectsusingblock:^ (NSString *obj, Nsuinteger idx, BOOL *stop)            {if ([obj isequaltostring:itemstr]) {index = (int) idx;        *stop = YES;        }    }];            Switch (index) {case 0:return [[Zypricesnoraml alloc] init];        Break      Case 1:return [[Zypricesreturn alloc] initwithmoneycondition:300 moneyreturn:100];      Break            Case 2:return [[Zypricesdiscount alloc] initwithmoneyrebate:0.8];    Break } return nil;} @end

In-Controller code: #import "ViewController.h" #import "ZYPricesTool.h" #import "ZYPricesNoraml.h" #import "ZYPricesDiscount.h" # Import "ZYPricesReturn.h" @interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {    [ Super Viewdidload];    Additional setup after loading the view, typically from a nib.        Zytotalprices *totalprices = [Zypricestool createtotalpriceswithitemstr:@ "hit 80 percent"];        Totalprices.number = 5;    Totalprices.singleprices = 6;        NSLog (@ "%lf", [totalprices totalprices]);} @end

This time, no matter how the product ran over the requirements of how to modify, can be very simple to achieve. For example, to "full 500 back to 200", directly in the Zypricestool to add a good, the algorithm does not need to re-write. If there is a demand, "full 100 yuan rebate points 10 points, a shopping to a certain point, give gifts", directly produce a subclass inherited from Zytotalprices, in which the algorithm to generate integral, and then in the tool class to add response processing can, other already processed classes, No need to change it at all.

However, it is also the pros and cons, although the simple factory design pattern solves the problem, but this model only solves the problem of object creation, and because the factory itself contains all the charging methods, the mall is likely to change the discount quota and rebate quota, each maintenance and expansion of the charge method to change the factory class, So that the code needs to be recompiled and deployed, that's a bad way to handle it. There should be a better design approach to the constant changes in the algorithm ...

4. Policy mode

The policy pattern defines the algorithm family, which is encapsulated separately so that they can be replaced with each other, and this pattern allows the algorithm to change without affecting the client using the algorithm.

Shopping malls when the sale of silver, with discount or rebate, in fact, are some algorithms, with the factory to generate algorithm objects, this is true, but the algorithm itself is only a strategy, the main thing is that the algorithm itself can be replaced at any time, this is the change point, and the package change point is an object-oriented way of thinking.

The next step is the policy mode code:

#import <Foundation/Foundation.h> @interface Zytotalprices:nsobject@property (nonatomic, assign) double singleprices; @property (nonatomic, assign) int number;/** *  So, there is a method declaration in the abstract class that is given to the subclass * */-(double) totalprices; @end # Import "ZYTotalPrices.h" @implementation zytotalprices@end

#import "ZYTotalPrices.h" @interface zypricesnoraml:zytotalprices@end#import "ZYPricesNoraml.h" @implementation zypricesnoraml/** *  Normal charge * */-(double) totalprices{    return self.singleprices * self.number;} @end

#import "ZYTotalPrices.h" @interface zypricesdiscount:zytotalprices/** *  discount rate for decimals */@property (nonatomic, assign) Double moneyrebate;-(Instancetype) Initwithmoneyrebate: (double) moneyrebate; @end #import "ZYPricesDiscount.h" @ Implementation zypricesdiscount-(Instancetype) Initwithmoneyrebate: (double) moneyrebate{    if (self = [super init]) {        self.moneyrebate = moneyrebate;    }    return self;} -(double) totalprices{    return self.number * self.singleprices * self.moneyrebate;} @end

#import "ZYTotalPrices.h" @interface zypricesreturn:zytotalprices/** *  Rebate Condition */@property (nonatomic, assign) double moneycondition;/** *  Rebate Value */@property (nonatomic, assign) Double moneyreturn;-(instancetype) Initwithmoneycondition: (Double) moneycondition Moneyreturn: (double) moneyreturn; @end #import "ZYPricesReturn.h" @ Implementation zypricesreturn-(Instancetype) Initwithmoneycondition: (double) moneycondition MoneyReturn: (Double) moneyreturn{    if (self = [super init]) {        self.moneycondition = moneycondition;        Self.moneyreturn = Moneyreturn;    }    return self;} -(double) totalprices{    Double total = Self.number * self.singleprices;    Return total-(int) (total/self.moneycondition) * Self.moneyreturn;} @end

#import <Foundation/Foundation.h> @class zytotalprices; @interface Zypricescontent:nsobject@property ( Nonatomic, Strong) zytotalprices *totalprice;/** * The corresponding algorithm object must be created according to the corresponding ITEMSTR string * */-(Instancetype) Initwithitemstr: ( NSString *) itemstr;-(double) getresult; @end #import "ZYPricesContent.h" #import "ZYTotalPrices.h" #import " ZYPricesNoraml.h "#import" ZYPricesDiscount.h "#import" ZYPricesReturn.h "@implementation zypricescontent-(    Instancetype) Initwithitemstr: (NSString *) itemstr{if (self = [super init]) {[Self commitinit:itemstr]; } return self;} -(void) Commitinit: (NSString *) itemstr{if ([Itemstr isequaltostring:@ "normal charge"]) {self.totalprice = [[Zypricesnor    AML Alloc] init]; } else if ([Itemstr isequaltostring:@ "full 300 return"]) {self.totalprice = [[Zypricesreturn alloc] Initwithmoneycondi    tion:300 moneyreturn:100];    } else {self.totalprice = [[Zypricesdiscount alloc] initwithmoneyrebate:0.8]; }}-(double) getresult{return [Self.totalpRice totalprices];} @end

Looking closely at this code, you will find, and the above with the factory call code basically no change, just the tool class, changed to the Zypricesreturn class, this class contains Zytotalprices class, holding Zytotalprices object, There is the original in the tool class to judge, the specific call which algorithm object, also in the Zypricesreturn class inside the implementation, can say, Zypricesreturn class is to zytotalprices service.

Look at the code inside the Viewcontroller, you can see the obvious difference, you can also understand the advantages of the strategy model:

First, call the Viewcontroller code of the tool class:

#import "ViewController.h" #import "ZYPricesTool.h" #import "ZYPricesNoraml.h" #import "ZYPricesDiscount.h" #import " ZYPricesReturn.h "@interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {    [super Viewdidload];    Additional setup after loading the view, typically from a nib.        Zytotalprices *totalprices = [Zypricestool createtotalpriceswithitemstr:@ "hit 80 percent"];        Totalprices.number = 5;    Totalprices.singleprices = 6;        NSLog (@ "%lf", [totalprices totalprices]);    } @end

It can be obvious that this method is implemented, Viewcontroller want to invoke various algorithms, then we have to include the various algorithms of the header file, create and hold a variety of algorithm objects.

So, what is the code inside the Viewcontroller if it's the code that implements the policy pattern:

#import "ViewController.h" #import "ZYPricesContent.h" #import "ZYTotalPrices.h" @interface Viewcontroller () @ End@implementation viewcontroller-(void) viewdidload {    [super viewdidload];        Zypricescontent *content = [[Zypricescontent alloc] initwithitemstr:@ "full 300 return"];    Content.totalPrice.number = 5;    Content.totalPrice.singlePrices = +;        NSLog (@ "%lf", [content GetResult]);} @end

Can see, viewcontroller only need to know zytotalprices and zypricescontent These two classes, do not need to know the various algorithm classes, greatly reducing the coupling degree.

Back to reflect on the strategy model, the strategy model is a method of defining a series of algorithms, conceptually, all of these algorithms do the same work, but the implementation is different, he can call all the algorithms in the same way, reducing the various algorithm classes and using the coupling between the algorithm classes.

The strategy pattern is used to encapsulate the algorithm, but in practice we can use it to encapsulate almost any type of rule, as long as you hear the need to apply different business rules at different times during the analysis, consider the possibility of using a policy pattern to handle this change.

Design pattern of the Strategy mode (iOS development, code with OBJECTIVE-C show)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.