views:

292

answers:

1

I have a bunch of functions which returns commonly used UIViews in my application, e.g.

+ (UIView *) getLikeRow:(CGRect) frame ofType:(LikeType) type

So far I've been using static methods for that, but recently I also noticed the sharedManager concept. Now I'm wondering if I should rather use a sharedManager for that.

What are the differences and advantages/disadvantages of using static methods vs. instance methods of a sharedManager singleton?

+4  A: 

You use the singleton/shared-managed pattern when it is important that only one instance of a class be alive at anyone time.

For example, it is important that an app have one and only one instance of UIApplication. You would want two instances of the application object because it would be impossible to keep them both in the same state. NSFileManager uses the pattern to prevent the app from having two file operations that collide with each other.

Enforcing a unique instance at runtime is the only valid reason to use the singleton/shared-managed pattern.

In your case, you just need a convenient place to park some utility class methods that don't require a live instance in order to function. The best way to handle that is to create a utility class that bundles all the class methods together. Then to use the methods, you just send to the class name like so:

UIView *theView=[MyViewUtilityClass getLikeRow:aRect ofType:aType];

This causes the MyViewUtilityClass to call the method from anywhere in the app without having to initialize an object. It's easier and neater than keeping a unique instance alive. If you use the utility methods throughout your app, you can add the header to the .pch universal header and all your custom classes will get the utility class automatically.

However, just like the singleton pattern, utility class methods can tempt you into becoming lazy and overusing them in places they don't really belong. Overused, they begin to make the app look like an old school, non-object oriented C collection of independent functions. This breaks encapsulation and modularity and makes your program a tangle of procedural code.

So, be careful that you are only putting the most generic and most universal functions into the utility class. If you have a lot of functions that deal with a specific class, such a UIView and subclasses, then you should put the functions in a category on that class.

TechZen
Makes sense. Thanks for the very elaborate and helpful answer.
znq