Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

language agnostic - Purpose of singletons in programming

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever created.

This sounds a lot like a static class to me. The main difference being that with a static class you don't / can't instance it, you just use it such as Math.pi(). With a singleton class, you would still need to do something like

singleton firstSingleton = new singleton();
firstSingleton.set_name("foo");

singleton secondSingleton = new singleton();

Correct me if i am wrong, but firstSingleton == secondSingleton right now, yes?

secondSingleston.set_name("bar");
firstSingleton.report_name(); // will output "bar" won't it?

Please note, I am asking this language independently, more about the concept. So I am not worried about actually how to code such a class, but more why you would wan't to and what thing you would need to consider.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The main advantage of a singleton over a class consisting of statics is that you can later easily decide that you need in fact more than one instance, e.g. one per thread.

However, in practice the main purpose of singletons is to make people feel less bad about having global variables.

A practical example for a good use of a singleton: you have an app that uses an SQL database and you need a connection pool. The purpose of such a pool is to reuse DB connection, so you definitely want all clients to use the same pool. Thus, having it as a singleton is the correct design. But one day you need the app to connect to a second DB server, and realize that you cannot have connections to different servers in the same pool. Thus your "one instance overall" singleton becomes "one instance per DB server".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...