开发者

Singleton Pattern Controversy with Factory Pattern [closed]

As it currently stands, this question is not a good fit for our Q&A format. We ex开发者_如何转开发pect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

Often I use factory Pattern when there are complexities around object creations and that complexities incorporates informations inaccessible (should not be accessible)to the creation scope or creation incorporates some mandatory unavoidable workarounds.

Often I make the Factory a Singleton cause there is no need to multiple factories. and passing the same factory to multiple classes looks so odd. passing a whole Factory in parameter

There have been a lot of controversies regarding Singleton Pattern. So Should I make Factory a Singleton still ?

The Factory needs to accessible to every corners that need the factory to produce some product . that requires passing that factory as an argument. and again passing that in a chain. and that chain will not be unidirectional. that will easily make branches. that will also lead to testing difficulties.


A class needn't be a singleton to provide a shared instance, and the fact that you only have one instance doesn't mean that the class must be a singleton. If you must have no more than one instance, that's the place to use a singleton. There's nothing in the Factory pattern that requires that you have only one factory -- it's easy to imagine having several factories each configured differently and each creating differently configured objects.


I'll side with Doug T.

You can very easily create a static function within a class which can be used to create an instance of that class (factory function). Better yet, you can create a factory class, and make the static function in the factory class generate the desired object. C# actually provides static classes where all members and functions are static for purposes like this - it's essentially a singleton anyway.

The point here is, whatever you do, it may make more sense to simply pass a function pointer to a factory function as your parameter. You'll have flexibility with where to store your creation logic then, and you can choose to avoid singletons/extra classes altogether.

(PS: I think singletons are a good pattern, but if you over-use them they become an anti-pattern because they reduce a design to something resembling just having global functions and data).


No you shouldn't, in fact singleton pattern is often seen almost as an antipattern from someone.

The best thing would be to rely on some IOC container avoiding both singleton both factory pattern.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜