It seems like I see a lot of class methods in Objective C that are like +(NSString*)stringWithString:(NSString *)string or +(NSArray)arrayWithArray:(NSArray *)array, etc. I am just starting to consider design patterns and to me these methods look like little factories that produce specific implementations of strings or arrays based on the paramaters provided (stringWith string , string ByAppendingString). In essence this looks a lot like the factory method with parameters demonstrated in the book Design Patterns. Is there a better way to do this? Should I be creating interfaces that mix these class methods and instance methods, or create Factory only objects that do not have any instance methods? I am confused.
It seems like I see a lot of class methods in Objective C that
Share
While Apple claims that these methods are factory methods, I argue that they’re not the same as the Factory Method pattern in Design Patterns. The DP Factory Method pattern uses an abstract
Creatorclass, with concrete subclasses that generate concreteProductclasses. The methods you’re describing (which are often called “convenience constructors”) are almost never implemented that way. Apple’s definition of a factory method is “a class method that, as a convenience to clients, creates an instance of a class. A factory method combines allocation and initialization in one step and returns an autoreleased instance of the class.” That’s why I believe the term “convenience constructor” is more appropriate and less confusing that “factory method.”NSStringis a class cluster, which has some passing similarities to the Factory Method pattern, in that you can receive different concrete classes from the same method call. But class clusters are different than Factory Method in that the superclass knows about all the subclasses, and it is the superclass that callers interact with. In the Factory Method pattern, callers interact with subclasses of the Creator class.So to your question: you should create convenience methods when it is convenient to the caller. It supplements:
with
My experience building these is that 90% of the time you shouldn’t. It’s not worth the extra code. You should wait until you see that
initWithSomething:is being called a lot with anautoreleaseright after it, and then you add a convenience constructor to make things more convenient. Things likestringWith...are in this class. They’re called a lot.