Search code examples
iosobjective-cfactory-pattern

What is the syntax and use of a factory method in Objective-C


I have been searching the web trying to understand what factory methods are but I haven't found any simple example that shows a concrete example. One of the books I have briefly talks about them but it doesn't show an example nor gives an explanation of what they are "Class methods are commonly used as factory methods".

1- What is the syntax and use of a factory method in Objective-C? This is the closest answer I found but when I tried the example in the comment maked as the answar I got a message saying that I couldn't call super. In this question I'm more concern about the syntax of the implementation of the factory method.

2- Are factory methods what are called constructors in other languages?

3- How are factory methods compared to Singletons?

From Apple documentation:

They combine allocation and initialization in one step and return the created object

Is not what singleton does?

In the following singleton example, can we say that the class method sharedData is a factory method?

.m File

#import "SingletonModel.h"
@implementation SingletonModel
static SingletonModel *sharedData;

- (id) init {
    if (self = [super init]) {
        // custom initialization
    }
    return self;
}

 // is this a factory method?
+(SingletonModel*) sharedData
{
    if (!sharedData) {
        sharedData = [[SingletonModel alloc]init];
    }
    return sharedData;
}
@end

Solution

  • What is the syntax and use of a factory method in Objective-C

    If we take UIColor as an example, factory methods would be + (UIColor *)blackColor, + (UIColor *)clearColor, ...

    From the other question you reference, any init... method should be an instance method (- (...), not + (...)). In that answer it is a class method and it shouldn't be.

    Are factory methods what are called constructors in other languages

    They all have the same purpose. Not all languages differentiate between allocation of memory and initialisation of that memory.

    How are factory methods compared to Singletons

    A singleton usually offers a single method to return the single instance of the class. It isn't strictly a factory method as it doesn't create a different instance each time it's called, but it is the same kind of thing.