Search code examples
objective-cswiftconstructorinitializerfactory-method

difference between factory methods and constructors


learning Objective and Swift at the moment. I understand initialisers in Obj C and convenience initialisers and I understand Factory methods. I have also heard the term "constructors" but I am not sure how they differ from factory methods or initialisers. Is "constructor" just another way to refer to initialisers? thanks


Solution

  • There is no difference.

    For a long time class methods that create instance objects had been called convenience allocators or – rarely – constructors. The term convenience allocators often has been used, when an instance object was autoreleased, what became unimportant with ARC.

    NSString *string1 = [NSString string]; // autoreleased
    NSString *string2 = [NSSString new];   // ownership transfer
    

    Basically they are a combination of +alloc and -init… plus – when it is a convenience allocator – -autorelease. Two (?) years ago or so the started to call them factor methods.

    However, forget about names. Think about what they do and why they exist: With a classical +alloc--init… combination the class had no chance to decide, what subtype to create, because that depends on the arguments of -init. Let's have an example: NSSArray has two (private) subclasses _NSSmallArray and _NSBigArray. It wants to chose the subtype from the estimated size you give as capacity on an -initWithEstimatedSize: method. How can +alloc decide, which subtype to chose and allocate? It has no idea, what argument you will pass on the init method.

    With constructors or convenience allocators, object allocation can be parametrized. +newArrayWithEstimatedSize: or +arrayWithEstimatedSize: can solve that problem.

    Eh, now you have to call them factory methods. Sorry. The story is the same.