iOS design mode-(3) Simple Factory mode

Source: Internet
Author: User


iOS design mode-(3) Simple Factory mode by Colin,

Reprint Please specify source: http://blog.csdn.net/hitwhylz/article/details/40381721


One. Briefly


Simple Factory mode (FACTORY), which reduces program coupling through object-oriented encapsulation, inheritance, and polymorphism. The instantiation of a specific class is given to a static factory method to execute.

The roles in this pattern include:

    • Factory class (Simple Factory): Contains only static methods that create concrete classes.
    • Abstract Product: Defines the products to be returned in a simple factory.
    • Specific Products (CONCRETEPRODUCT): Specific products.
We use a class diagram to describe this pattern. Here, the customer class and the factory class are separated. Consumers need a product at any time, just request it from the factory. Consumers can accept new products without modification. ProductA, PRODUCTB, and PRODUCTC inherit from the product virtual class, and the Show method is a self-describing of different products; factory relies on ProductA, PRODUCTB, and PRODUCTC, Factory create different product objects based on different conditions. Two. Examples involve code downloads: For example, if we want to implement a calculator function, it contains a +-*/and other basic operations. It functions roughly as follows: Before we use design mode, we routinely write code like this:
-(Ibaction) GetResult: (ID) sender{//Get the contents of three text input boxes nsstring* strfirstnum = self.    Firstnumtextfield.text; nsstring* strsecondnum = self.    Secondnumtextfield.text; nsstring* stroperation = self.    Operationtextfield.text;        Operation Operations 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 (@ "/");        The judgment divisor cannot be 0 if ([strsecondnum isequaltostring:@ "0"]) {NSLog (@ "divisor cannot be 0"); uialertview* Tempalert = [[Uialertview alloc] initwithtitle:@ "Warning" message:@ "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, write a method by passing in the value. To calculate. The above code does do this, but we do not consider: if you need to provide the open square operation, the power of the expansion of the operation, how to do? Add an if else directly if you add 100 operations? If this is not always going to change this part of the code, this is contrary to our extensibility principle. So we need to introduce the simple factory pattern, abstract the operation, and join the arithmetic factory to receive the user's operation.

First look at the implementation class diagram of the simple factory:

According to this idea. We can write the following code:
Protocol interface:
#import <foundation/foundation.h>/*! *  operation Method Protocol interface * *  @since V1.0 */@protocol Operationprotocol <nsobject>-(double) getresult; @end


Parent class: Implements an interface that indicates that it has a GetResult method
#import <Foundation/Foundation.h> #import "OperationProtocol.h"/*! *  Operation Method Parent class * *  @since V1.0 */@interface operation:nsobject<operationprotocol> @property double firstnum;// The first operand @property a double secondnum;//the second operand @end

Subclass: (take addition as an example)
#import "Operation.h"/*! *  Addition Implementation class * *  @since V1.0 */@interface Operationadd:operation@end

Realize:
#import "OperationAdd.h" @implementation operationadd-(double) getresult{    double result = 0;    result = Self.firstnum+self.secondnum;    return result;} @end

Other operations are similar and are not duplicated.
Factory class:
#import <Foundation/Foundation.h> #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 Action 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, a concrete class of operation methods is created through the factory class.
And we in the client part, as long as the corresponding method can be passed, do not need to know its specific implementation process, as follows:
-(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 refactoring of the simple Factory mode, we implemented the code structure with low coupling, which was open to expansion and closed for modification. If you add any additional operations, simply inherit the action method parent class, create a new action subclass, and add an if else judgment in the factory method. How simple it is.
This is probably the case, now make a summary:
Three. Summarize
Advantages:
    • The function is simple, and the decoupling of client code and concrete implementation is realized.
    • The factory class is the key to the whole pattern. Contains the necessary logical judgments, based on the information given by the outside world, to determine exactly which specific class of objects should be created.
    • By using the factory class, outsiders can get rid of the embarrassing situation of directly creating specific product objects, just need to be responsible for the "consumption" object. Without having to worry about how these objects are created and how they are organized.
    • The respective responsibilities and rights are clarified, which facilitates the optimization of the whole software architecture.
Disadvantages:
    • Because the factory class centralizes all instances of the creation logic, violates the cohesion responsibility allocation principle, the whole creation logic is concentrated in a factory class, it can create the class can only be considered beforehand, if you need to add new classes, you need to change the factory class. It is therefore contrary to the principle of open closure.
    • As the number of specific product classes in the system increases, there may be a need for factory classes to create different instances based on different conditions. This kind of judgment of the condition and the judgment of the specific product type staggered together, it is difficult to avoid the spread of the module function, the maintenance and expansion of the system is very unfavorable;
Note: These shortcomings have been overcome in the factory method model.
Usage scenarios:
    • The factory class is responsible for creating fewer objects;
    • The customer knows only the parameters of the incoming factory class and does not care about how to create the object (logic);
    • Because simple factories can easily violate the principle of high cohesion responsibility allocation, they are generally used only in very simple cases.


study on the road, with June encouragement

iOS design mode-(3) Simple Factory mode

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.