IOS design model-(3) simple factory Model

Source: Internet
Author: User

IOS design model-(3) simple factory Model

 

 

I. Brief Introduction

 

 

The simple FACTORY mode reduces the coupling of programs through object-oriented encapsulation, inheritance, and polymorphism. Instantiate a specific class to a static factory method for execution.

Roles in this mode include:

 

Simple Factory: only static methods for creating specific classes are included. Abstract Product: defines the Product to be returned in a simple factory. Specific product (ConcreteProduct): specific product. We use a class diagram to describe this mode. Here, the customer class and the factory class are separated. A consumer needs a product at any time and only requests from the factory. Consumers can accept new products without modification. ProductA, ProductB, and ProductC inherit from the Product virtual class. The Show method is the self-description of different products. Factory depends on ProductA, ProductB, and ProductC. Factory creates different Product objects according to different conditions. II. The instance involves code downloading: for example, if we want to implement a calculator function, it contains basic operations such as +. its functions are roughly as follows: before using the design mode, we normally write the following code:
-(IBAction) getResult :( id) sender {// get the content of the three text input boxes NSString * strFirstNum = self. firstNumTextField. text; NSString * strSecondNum = self. secondNumTextField. text; NSString * strOperation = self. operationTextField. text; // perform operation if ([strOperation isEqualToString: @ +]) {NSLog (@ +); double result = [strFirstNum doubleValue] + [strSecondNum doubleValue]; self. resultTextField. text = [NSString stringWithFormat: @ % f, result];} else if ([strOperation isEqualToString: @-]) {NSLog (@-); double result = [strFirstNum doubleValue]-[strSecondNum doubleValue]; self. resultTextField. text = [NSString stringWithFormat: @ % f, result];} else if ([strOperation isEqualToString: @ *]) {NSLog (@*); double result = [strFirstNum doubleValue] * [strSecondNum doubleValue]; self. resultTextField. text = [NSString stringWithFormat: @ % f, result];} else if ([strOperation isEqualToString: @/]) {NSLog (@/); // determine that the divisor cannot be 0 if ([strSecondNum is1_tostring: @ 0]) {NSLog (@ divisor cannot be 0); UIAlertView * tempAlert = [[UIAlertView alloc] initWithTitle: @ warning message: @ the divisor cannot be 0 delegate: nil cancelButtonTitle: @ cancel otherButtonTitles: nil]; [tempAlert show];} else {double result = [strFirstNum doubleValue]/[strSecondNum doubleValue]; self. resultTextField. text = [NSString stringWithFormat: @ % f, result] ;}}

That is, a method is written to calculate the input value. The code above can indeed implement this function, but we have not considered it: if we need to provide square operations in the future, how can we change the formula when the multiplication operation is extended? Directly add an if else? What if we add 100 types of operations? If we do this, do we need to modify this part of code every time? This is against the principle of scalability. Therefore, we need to introduce the simple factory mode, abstract the operations, and add the operation factory to receive user operations.

Let's take a look at the implementation class diagram of a simple factory:

Based on this idea, we can write the following code:
Protocol interface:
# Import
 
  
/*! * Operation method protocol interface ** @ since V1.0 */@ protocol OperationProtocol
  
   
-(Double) getResult; @ end
  
 


Parent class: Implementation interface, indicating that it has the getResult Method
# Import
 
  
# Import OperationProtocol. h /*! * Operation method parent class ** @ since V1.0 */@ interface Operation: NSObject
  
   
@ Property double firstNum; // The first operand @ property double secondNum; // The second operand @ end
  
 

Subclass: (using addition as an example)
# Import Operation. h /*! * Addition implementation class ** @ since V1.0 */@ interface OperationAdd: Operation @ end

Implementation:
#import OperationAdd.h@implementation OperationAdd-(double)getResult{    double result = 0;    result = self.firstNum+self.secondNum;    return result;}@end

Other operations are similar and will not be repeated.
Factory type:
# Import
 
  
# Import Operation. h # import OperationAdd. h # import OperationSub. h # import OperationMultiply. h # import OperationDivide. h /*! * Operation factory class ** @ since V1.0 */@ interface OperationFactory: NSObject // get Operation object + (Operation *) createOperate :( NSString *) operateStr; @ end
 

#import OperationFactory.h@implementation OperationFactory+(Operation*)createOperate:(NSString*)operateStr{    Operation* oper = nil;    if ([operateStr isEqualToString:@+])    {        oper = [[OperationAdd alloc] init];    }    else if ([operateStr isEqualToString:@-])    {        oper = [[OperationSub alloc] init];    }    else if ([operateStr isEqualToString:@*])    {        oper = [[OperationMultiply alloc] init];    }    else if ([operateStr isEqualToString:@/])    {        oper = [[OperationDivide alloc] init];    }    return oper;}@end

Here, the specific class of the calculation method is created through the factory class.
On the client side, we only need to pass in the corresponding method, without having to know the specific implementation process, as shown below:
- (IBAction)clickingOperation:(id)sender{    NSString* strFirstNum = self.firstNumTextField.text;    NSString* strSecondNum = self.secondNumTextField.text;    Operation* oper;    oper = [OperationFactory createOperate:self.operationTextField.text];    oper.firstNum = [strFirstNum doubleValue];    oper.secondNum = [strSecondNum doubleValue];    self.resultTextField.text = [NSString stringWithFormat:@%f,[oper getResult]];    }

Through the reconstruction of the simple factory model, we have implemented the code structure with a low Coupling Degree, made it open to expansion and closed to modification. If you add any operation method, you only need to inherit the operation method parent class, create an operation subclass, and add an if else judgment in the factory method. It's easy.
This is probably the case. Now let's make a summary:
3. Summary
Advantages:
Single responsibility, simple implementation, and decoupling of client code from specific implementation. The factory class is the key to the entire model. it contains the necessary logical judgment to determine the specific class object to be created based on the information given by the outside world. by using the factory class, the outside world can get rid of the embarrassing situation of directly creating specific product objects, and only need to be responsible for "consuming" objects. Without having to worry about how these objects are created and organized, they clearly define their respective responsibilities and rights, which is conducive to the optimization of the entire software architecture. Disadvantages:
Because the factory class integrates the creation logic of all instances, in violation of the High Cohesion responsibility allocation principle, all creation logic is centralized into a factory class; the class it can create can only be considered in advance, if you need to add a new class, you need to change the factory class. Therefore, it violates the open and closed principle. When the number of product categories in the system increases, the requirements for the factory category to create different instances based on different conditions may arise. this kind of judgment on the condition is intertwined with the judgment on the specific product type, and it is difficult to avoid the spread of module functions, which is very unfavorable for system maintenance and expansion. Note: these shortcomings have been overcome in the factory method model.
Use Cases: The factory class is responsible for creating fewer objects. The customer only knows the parameters passed in to the factory class and does not care about how to create objects (logic; because simple factories are easy to violate the High Cohesion responsibility allocation principle, they are generally used only in simple cases.

On the way to learning, I will share with you

 

Related Article

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.