Question

I went through the source code of GNUStep's NSNumber's implementation to understand how does factory method implementation works there.

From there What I could understand was we have NSNumber with blank implementation for all initWithXYZ kind of methods. and NSTemporaryNumber was acting like an intermediate class in the hierarchy that implemented all the initWithXYZ methods where it actually created objects of specific types , autoreleased itself and returned the created object.

Also allocWithZone was overridden to avoid creation of NSNumber object and to create object of NSTemporaryNumber if it was so otherwise create objects of specific types.

What I didn't understand was, can't the same things be done by NSNumber itself ? why give blank implementations at all , create the object of specific type and then autorelease self.

Also if we have implementations of createXYZ methods in NSNumber itself, why have initWithXYZ methods ?

If I have to implement a factory implementation for my project where say I have two mediaItems, video , audio and photo etc. for which I have separate classes and corresponding enums which I pass to initWithMediaType who will create an object of correct child class, return it and destroy itself.

Have two classes like NSNumber and NSTemporaryNumber: say Media and TemporaryMedia, one with blank implementations other with implementations as mentioned above ?

Should I do something like this ? Is this the way we have to implement Factory pattern in Objective C ?

My question might seem silly biut I come from a Java, C++ background where things looked different. The purpose might be the same but I am finding it difficult to understand the way Objective C does it since it does not have abstract classes.

Link to the source: http://www.koders.com/objectivec/fid46956186C20201706AFE1744AA7AFEEE09D1FE5A.aspx

Was it helpful?

Solution

The point is that NSNumber is a class cluster. The class you actually end up with may be an NSIntNumber, an NSFloatNumber or one of several others. They all respond to the same messages as NSNumber (and, usually in this pattern will be subclasses of it, but that isn't required) so it makes no real difference to the caller.

When you call alloc there's no way to know what sort of object to create, so a neutral type is created and returned instead. It substitutes appropriately upon receiving an appropriate init.

So this pattern is for the implementation of class clusters. You can ignore it if writing a class that provides only instances of itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top