开发者

Can we create only a Single object for a class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, 开发者_如何学编程incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

Is it possible to create only single object to the class?. How to do that in Java?


The following class definition is a Singleton Pattern:

public class Singleton {

    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

The only way to retrieve an instance of the Singleton object for this class is to call the getInstance() method which insures that there will always be one instance of the Singleton object.


As the other answers suggest, the Singleton Pattern can guide your implementation so you create only a single instance of a class ... or not.

Truth is, many factors come into play, in particular if you're working under a managed environment, like an application server on top of a Java virtual machine. In that case, there can be multiple servers in a cluster, each server can start multiple JVMs, and each one can start multiple classloaders, each one of them creating a different instance of the "singleton" class. So, there is no way to guarantee that a single instance of an object will exist, for a given class!

Besides, many people thinks that singletons are evil, and you should consider carefully if you really need to use one, and whether your environment will allow it.


The simplest way to do this is to use an enum

enum Singleton {
   INSTANCE;
}

The class is lazy loaded and thread safe.


You should look at the Singleton Pattern

If you can provide details about language, It would be easy to provide an example.


Depends. Usually creating only one object of a class smells of Singleton pattern.

Either you do not create any objects and use only class variables and methods or you use a proxy method.

Something like:

public static Object getInstance(){
  if(self.instance == null) {
    self.instance = new Object();
  }
  return self.instance;
}

Instead of calling new Object() in client side code you only call getIntstance();


If you're asking how to implement the Singleton pattern, I recently came across an excellent article, Implementing Singleton in C#, which gives code examples and covers some potential issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜