Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Instance vs Class Methods

While recently working with Objective-C and various libraries written in it, I've noticed two really popular singleton patterns. One version fetches the singleton instance and calls its instance methods and other version only exposes class methods and never gives you an instance to work with. All have the purpose of abstracting access to a single resource (StoreKit, CoreData, Parse API etc.). For example, here's the former approach used in MKStoreKit:

// initialize singleton during app boot [MKStoreManager sharedManager]  // sometime later in the app [[MKStoreManager sharedManager] buyFeature:kFeatureAId                                  onComplete:^(NSString* purchasedFeature)  {      NSLog(@"Purchased: %@", purchasedFeature);  }                                onCancelled:^  {      NSLog(@"User Cancelled Transaction");  }]; 

or alternatively NSUserDefaults, UIApplication etc.. The other approach can be seen in MagicalRecord or here with Parse API:

// configure API credentials sometime during app boot [Parse setApplicationId:@"123456"               clientKey:@"123456"];  // sometime later PFObject *testObject = [PFObject objectWithClassName:@"TestObject"]; [testObject setObject:@"bar" forKey:@"foo"]; [testObject save]; 

What are some pros and cons of the two approaches and is one of them fundamentally better than the other?

Not having to retrieve the shared instance saves some screen estate (the performance difference is likely irrelevant), but am I screwing myself in some other way, for example, testability-wise?

Thanks!

like image 970
Alexandr Kurilin Avatar asked Nov 02 '12 03:11

Alexandr Kurilin


People also ask

What is the difference between instance and class methods?

Key Takeaways. Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .

What is the difference between the Singleton pattern and a class with all methods static?

While a static class allows only static methods and and you cannot pass static class as parameter. A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.

Can singleton class have methods?

In case of singleton classes there is no use of static methods as there is only one instance available of the class and every buddy is having the same copy of it.

What is the difference between singleton class and singleton design pattern?

Singleton classes can be used as a method parameter. Static class cannot be used as a method parameter. Singleton pattern uses Heap memory. Static classes use stack memory.

How to design a singleton class in Java?

To design a singleton class: Make constructor as private. Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization in used to write this static method.

Should I use singleton or static classes in my application?

When developing applications in .NET Core, you might often need a single, shared instance of a class. Typical use cases would be an instance of LogManager, StateManager, etc. You can either use a singleton class or a static class to achieve this. The decision on which to choose—singleton or static—depends on several factors.

What is the use of getInstance() method in singleton class?

In a singleton class, when we first time call getInstance () method, it creates an object of the class with name single_instance and return it to the variable. Since single_instance is static, it is changed from null to some object.

What is the difference between static and Singleton in Java?

Static and Singleton are very different in their usage and implementation. So we need to wisely choose either of these two in our projects. Let us discuss more about the Singleton class first. Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful.


2 Answers

There are two different ways to implement the approach based on class methods:

  • Make a singleton instance using a class hidden from everybody, and hide its methods behind wrapper class methods with identical signatures, or
  • Make class methods that do all the work

The implications of the first implementation are that everything you can do with a singleton, you can do with the hidden singleton:

  • using a subclass becomes a possibility
  • switching the instance in the middle of the run is easy
  • the state lives in instance variables
  • initialization follows the familiar pattern

If you go for an implementation that does not use a singleton, you would be relying on static variables to keep your current state. That is a legitimate choice, but the initialization pattern becomes different (perhaps even using a dispatch_once), you cannot switch the implementation in the middle without relying on some ugly if conditions, and using a subclass becomes a lot more tricky.

Testing the first implementation is somewhat easier than testing the second one, because you can provide a separate implementation of the singleton for testing, perhaps through the back door; with a static-based implementation, this route cannot be taken.

To summarize, I would use a singleton-based solution, with the singleton optionally hidden behind a "facade" that provides access to singleton's methods. I would not use an implementation where all state must be placed in static variables.

like image 142
Sergey Kalinichenko Avatar answered Sep 24 '22 18:09

Sergey Kalinichenko


One advantage of the singleton approach is that it becomes trivial to allow other instances if you need to. If you take the class method approach, that's all you get without a lot of refactoring.

like image 38
rmaddy Avatar answered Sep 25 '22 18:09

rmaddy