On design patterns: When should I use the singleto

2018-12-31 05:34发布

The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.

Give me scenarios, other than the good old logger where it makes sense to use the singleton.

18条回答
情到深处是孤独
2楼-- · 2018-12-31 05:56

Reading configuration files that should only be read at startup time and encapsulating them in a Singleton.

查看更多
爱死公子算了
3楼-- · 2018-12-31 05:56

1 - A comment on the first answer:

I don't agree with a static Logger class. this can be practical for an implementation, but it cannot be replaceable for unit testing. A static class cannot be replaced by a test double. If you don't unit test, you won't don't see the problem here.

2 - I try not to create a singleton by hand. I just create a simple object with constructors that allow me to inject collaborators into the object. If I needed a singleton, I'd use a dependency inyection framework (Spring.NET, Unity for .NET, Spring for Java), or some other.

查看更多
牵手、夕阳
4楼-- · 2018-12-31 05:57

You can use Singleton when implementing the State pattern (in the manner shown in the GoF book). This is because the concrete State classes have no state of their own, and perform their actions in terms of a context class.

You can also make Abstract Factory a singleton.

查看更多
何处买醉
5楼-- · 2018-12-31 05:59

An example with code, perhaps.

Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):

http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html

Ed.

查看更多
浮光初槿花落
6楼-- · 2018-12-31 06:01

You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.

Or a database connection or a file manager etc.

查看更多
谁念西风独自凉
7楼-- · 2018-12-31 06:01

I think singleton use can be thought of as the same as the many-to-one relationship in databases. If you have many different parts of your code that need to work with a single instance of an object, that is where it makes sense to use singletons.

查看更多
登录 后发表回答