iOS design mode-Factory mode

Source: Internet
Author: User

What is the factory method model?

The factory method is also known as a fictional builder, and it is suitable for situations where a class cannot anticipate which class of object it needs to generate, and wants its subclasses to specify the resulting object.

Factory method Pattern: Defines the interface that creates the object, letting the subclass decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses.

When to use Factory Method

@: The class of the object to be created cannot be accurately expected at compile time.

@: class wants subclasses to decide what to create at run time.

The @: class has several helper classes for its subclasses, and you want to localize the information that returns which subclasses.

The minimum of this pattern is that the factory method gives the class more flexibility in changing which object to return.

Using factory methods to create objects can count as a best practice compared to creating new concrete objects directly. The factory method pattern allows the client program to require that objects created by the factory method have a common set of behaviors. Therefore, it is not necessary to modify the client code to introduce new concrete products into the class hierarchy. Because the interface of any specific object returned is the same as the interface that the client has been using.

Applying factory methods in the Cocoa touch framework

For example NSNumber has many numberwith* methods, two of which are numberwithbool: and Numberwithchar:. They are class methods, which means we send [NSNumber Numberwithbool:bool] and [NSNumber Numberwithchar:char] to NSNumber to get the arguments with the incoming Various nsnumber instances of the same type. All details about how to create an instance of a specific subclass of NSNumber are the responsibility of the NSNumber class factory method. In the case of [NSNumber Numberwithbool:bool], the method accepts the value bool and initializes an instance of the inner subclass of the nsnumber so that it can reflect the value passed in bool.

Application of Factory methods

We use a protocol to let the factory object have the same method, in the protocol we declare a calculation method, used to do two number calculation, the code is as follows:

#import <Foundation/Foundation.h> @protocol Calculate <NSObject> @property (nonatomic, assign) float Numbera; @property (nonatomic, assign) float numberb;-(float) calculate; @end

Then we define two classes to calculate the calculations, namely the sum calculation and the multiplication calculation, the code is as follows:

#import <Foundation/Foundation.h> #import "Calculate.h" @interface addcalculate:nsobject <calculate>-( float) Calculate; Override this method @end
#import "AddCalculate.h" @implementation addcalculate@synthesize numbera = _numbera; @synthesize numberb = _numberb;-( float) Calculate {return self.numbera + Self.numberb;} @end
#import <Foundation/Foundation.h> #import "Calculate.h" @interface multiplycalculate:nsobject <calculate >-(float) calculate; @end
#import "MultiplyCalculate.h" @implementation multiplycalculate@synthesize numbera = _numbera; @synthesize Numberb = _ numberb;-(float) Calculate {return self.numbera*self.numberb;} @end

so the specific calculation has been implemented by these two classes, let's create the corresponding factory method, we first create an abstract factory class, the factory code is as follows:

#import <Foundation/Foundation.h> #import "Calculate.h" @interface factory:nsobject <calculate>-(ID) Createfactory; @end
#import "Factory.h" @implementation factory@synthesize numbera = _numbera; @synthesize Numberb = _numberb;-(ID)    createfactory {NSLog (@ "Specifically returns what object, subclass to determine"); return nil;} -(float) Calculate {return-1;//return by default-1} @end

from the code we can see that the abstract factory defines the interface of the object created by the factory method. However, the code for the Addfactory class is as follows: The specific return object to be determined by its subclasses .

#import "Factory.h" @interface addfactory:factory-(ID) createfactory; Override this method @end
#import "AddFactory.h" #import "AddCalculate.h" @implementation addfactory-(ID) createfactory {return [addcalculate al LOC] init];} @end

The multiplyfactory code is as follows:

#import "Factory.h" @interface multiplyfactory:factory-(ID) createfactory; @end
#import "MultiplyFactory.h" #import "MultiplyCalculate.h" @implementation multiplyfactory-(ID) createfactory {return [ [Multiplycalculate alloc] init];} @end

As we can see from the code, addfactory and multiplyfactory implement the Createfactory interface, which defines the factory method that returns the object. Below we look at how the client uses the Factory mode, the client code is as follows:

#import   "ViewController.h" #import   "Calculate.h" #import   "AddCalculate.h" #import   " MultiplyCalculate.h "#import   Factory.h" #import   "AddFactory.h" #import   "MultiplyFactory.h" @ interface viewcontroller  () @end @implementation viewcontroller-  (void) viewDidLoad {     [super viewDidLoad];        Factory  *factory = [[addfactory alloc] init];    factory *calculate  = [factory createfactory];    calculate.numbera = 10.0;     calculate.numberb = 20.0;        float sum  =  [calculate calculate];    nslog (@ "Sum is = %f",  sum);         factory *factory1 = [[ multiplyfactory alloc] init];    Factory *calculate1 = [factory1 createFactory];     calculate1.numbera = 10.0;    calculate1.numberb = 20.0;         float multiply =  [calculate1 calculate];     nslog (@ "sum is = %f",  multiply);         }-  (void) didreceivememorywarning {    [super  Didreceivememorywarning];    // dispose of any resources that  can be recreated.} @end

The output ends are as follows:

2015-09-04 22:51:06.298 factorypattern[49484:2688173] sum is = 30.0000002015-09-04 22:51:06.299 FactoryPattern[ 49484:2688173] multiply is = 200.000000

as we can see from this example, the factory method eliminates the coupling of the application-specific classes from the code. The code only needs to handle the factory abstract interface, so the same code can be reused, working with any specific user-defined class in the application.

Demo Link Address: https://github.com/guoshimeihua/FactoryPattern.git

iOS design mode-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.