开发者

singleton vs factory?

开发者 https://www.devze.com 2022-12-28 18:22 出处:网络
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'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 a开发者_如何学Cs multiple objects in the future.

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


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.


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.


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号