Tutorial :singleton vs factory?



Question:

i've got 3 Log classes that all implements iLog interface:

DatabaseLog  FileLog  ScreenLog  

there can only be one instance of them. initially i though of using single pattern for each class but then i thought why not use a factory for instantiation instead, cause then i wont have to create single pattern for each one of them and for all future Log classes.

and maybe someone would want them as multiple objects in the future.

so my questions is: should i use factory or singleton pattern here?


Solution:1

Where should responsibility for creating the Logger instance reside? With each class that wants to log? With some kind of supervisory component that understands the overall context?

I think it's more likely to be the latter, and hence a Factory will make sense. The faactory can have all the logic for deciding which kind of logging is needed.


Solution:2

The singleton and the factory pattern serve completely different purposes. This singleton-pattern is used to ensure that there is only ever one instance of a class. The factory-pattern is used to abstract object instantiation. You can use a factory to create a singleton, and factories themselves often are singletons, but there is no one vs the other. They are complementary rather than opposed patterns.

In your case, implementing the singleton-pattern makes sure you can have only one instance of each class. You can use a factory that does not create new instances if one already exists.

If you have an interface for logging, and several implementations for it (e.g. logging to file or logging to network), you can use a factory to instantiate the implementations dynamically, and hide the instantiation process, which might differ for each implementation (e.g. open a file or open a socket). You can still make your objects singletons if that is what you want.


Solution:3

Well if someone might want to create multiple objects of these types, then singleton is clearly out of question.

Create a factory that reads the type of the log from a config file (maybe) and return a ILog reference to the concrete type


Solution:4

Like others stated, I would also suggest using a factory. One advantage when not using Singletons is that you have no global state thus making your code much more testable.


Solution:5

I'd use a factory here, a singleton can't satisfy your requirement of one instantiation between all three classes.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »