Simple Factory mode sample code,
1. Brief introduction
First of all, the simple factory model does not belong to one of the 23 gof design modes. It is also known as the static working method pattern, which is a special implementation of the Factory method pattern (that is, the factory pattern contains a simple factory pattern). This introduction to the simple factory model is a primer for the factory approach and the abstract factory model behind it.
2. Definition
"specifically defines a class to be responsible for creating instances of other classes, and the instances that are created typically have a common parent class. ”
The world is made up of a factory class that dynamically decides which product class to create, based on the parameters passed in.
3. Structure diagram
Brief analysis of the structure diagram:
ConcreteProduct1 and ConcreteProduct2 two products have a common parent class iproject, the Simple factory class is simplefactory, responsible for the different parameters to determine the production ConcreteProduct1 or ConcreteProduct2 products.
4. Code sample explanation
Simulate a scenario that uses a calculator: The user can enter two numbers and manipulate symbols, and then get the results, using the interaction as shown, respectively, to perform the addition and subtraction operations,
(1) In addition to the operation example
(2) Examples of subtraction operations
A novice, very likely to follow their initial thinking logic, judge the user input operators, and then the two numbers to calculate, of course, plus the necessary divisor is not 0 of the judgment, then click the Operation button, the corresponding event can be written as follows,
- (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 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 (@ "/"); //judgment divisor cannot be 0 if ([strsecondnum isequaltostring:@ "0"]) { &nbSp; 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]; } }}
Well, it's certainly possible to write this function. However, if more operations are performed, such as increasing the square and the exponentiation, and adding 100 operations, is it not to add 100 else if judgment statements? If you do this every time you want to modify this part of the code, this is contrary to the principle of extensibility. So we need to introduce the simple factory pattern , abstract the operation, and join the arithmetic factory to receive the user's operation.
Note: Here we take the operation of this action to abstract out, as an object, many people may feel a little confused. We know that object-oriented programming is different from process-oriented programming, usually to abstract a thing into a class, the class has properties and methods, then we can also abstract an action, such as the operation Operation here, It has two properties (the previous operand and the last operand), and it has the method of getting the result of the operation. So in-depth understanding of object-oriented programming, there are many ways to go.
So here we can abstract a UML diagram, as shown below,
Similar to the UML structure diagram above, here is a simple explanation, plus, minus, multiply, except four operators inherit from the parent class operation, there are two properties and an action method, these subtraction objects are not created directly in Viewcontroller, but based on the input operator, Created by simple factory operationfactory.
(1) Create a protocol Oprationprotocol, operation by the parent class to comply with the protocol
/* * Operation Method Protocol interface */@protocol operationprotocol <nsobject>-(double) getresult; @end
(2) Define the parent class of the subtraction operation operation
#import operationprotocol.h/* * Action Method Parent class/@interface operation:nsobject<operationprotocol> @property Double firstnum;//the first operand @property a double secondnum;//the second operand @end
(3) Subtraction implementation class, here with "plus" example,
OperationAdd.h File #import operation.h/* * Addition implementation class */@interface operationadd:operation@end//operationadd.m file #import " OperationAdd.h "@implementation operationadd-(double) getresult{double result = 0; result = self.firstnum+self.secondnum;//"+" is used when Operationadd, "+-*/" corresponds to "subtraction" return result;} @end
(4) The code of the Simple factory class,
opeartionfactory.h file#import operation.h#import operationadd.h#import operationsub.h# import operationmultiply.h#import operationdivide.h/* * operation factory class */@interface operationfactory : nsobject //Get Operation Object + (operation*) Createoperate: (nsstring*) operateStr; @end//opeartionfactory.m file#import "OperationFactory.h" @implementation operationfactory + (operation*) Createoperate: (nsstring*) operatestr{ operation* oper = nil; //creates different operands according to different operators, "+-*/" corresponds to "subtraction" 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
(5) Client code, using Operationfactory in Viewcontroller
-(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];}
In this case, the code in Viewcontroller looks simple and easy to expand.
Then we analyze the use of ideas, according to the code in Viewcontroller, the Operation class analogy into a container, it has the input (operation symbol, the first operand, the second operand) and the output (the result of the operation), as shown in,
So the above code takes the input from the Viewcontroller TextField to create the operand, and puts the logic of the operation into the operation and its subclasses, and returns the result to Viewcontroller, This reduces the logic code for Viewcontroller.
Through the refactoring of the simple Factory mode, we are idle the code structure of the low coupling degree, so that the external expansion open, the modification is closed. If you add any additional action methods, simply inherit the action method parent class, create a new action subclass, and add an else if to the simple factory class.
V. Advantages and Disadvantages
Advantages: The advantage of the simple Factory mode is that the client can consume the product directly without concern for the implementation of the specific product, eliminating the responsibility of the client to create the product object directly, and realizing the division of responsibility.
The disadvantage is that the factory has several kinds of all product creation logic, once not working properly, the whole system will be affected, and when the product class multi-structure complex, put all the creation work into a factory, back to the late expansion of the program is more difficult.
Through the analysis of advantages and disadvantages, we can use the Simple Factory mode in the following scenario:
(1) When the factory class is responsible for creating fewer objects;
(2) The client knows only the parameters of the incoming factory class, and does not care about how to create the object's logic.
VI. Reference Blogs
(1) iOS design pattern Analysis Simple Factory mode (simplefactory)
(2) Design patterns in-depth learning iOS (2) Simple Factory mode
(3) Computer simple Factory mode sample code
iOS design mode (Code Analysis Series 2: Simple Factory mode)