views:

280

answers:

5

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?

+4  A: 

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.

djna
right, i think thats better to. cause then if someone else use my Log classes in another application, he could use another kind of logic. thanks
never_had_a_name
A: 

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

Michael
what do you mean between all three classes?
never_had_a_name
A: 

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

Midhat
+1  A: 

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.

Space_C0wb0y
A: 

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.

Helper Method