9

As per my thoughts, we should make a class as Singleton when we share the same object state across the application. In that case we want the user to to restrict from creating a new instance every time so that they could not maintain the multiple states. Agreed. But the same behavior can be acheved by by declaring the instance variables as static. To me it looks it will also serve the same purpose whether its cacheobjectcontainer, logger or Classloader class.

Please help me to understand above concept where static instance variable will not solve the purpose and class needs to be declared Singleton?

Edited Part

Ok let me bring some more clarity . The pupose of singleton class is to keep only one instance of singleton class across jvm. Agreed. But i am trying to think of reasons why we want to keep only one instance. There can be two reasons:

1) Object might be expensive to create. So we just want to keep only one instance. Agreed in this scenario declaring instance variables as static does not solve any purpose.

2) We want to share the same state of object across application. I was thinking this is the main purpose of declaring the class as singleton. But it can be achieved simply by declaring the instance variables as static.

But looks like 1 is the main reason of delaring any class as static not reason 2 because it can be achieved with static variable also.

Is this correct?

The Student
  • 27,520
  • 68
  • 161
  • 264
M Sach
  • 33,416
  • 76
  • 221
  • 314
  • 1
    can u elaborate your question by adding the names of a few classes and instances . that way, your question will be clearer. thanks. – anjanb Aug 26 '11 at 16:39
  • Possible duplicate of: http://stackoverflow.com/questions/4723245/singleton-class-static-properties-or-non-static-properties/4723304 – The Student Aug 29 '11 at 14:11

5 Answers5

11

Declaring the instance variable makes that reference a static object. Meaning there is only one instance of it for that class. But it doesn't stop anybody else from doing new SomeObject() regardless of if it is static reference. The idea of having a singleton class is to control the instances. For example, if you make the constructor private, you cannot do a new to create a new instance. Hence, you are controlling the creation of the instances.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • Thanks amir. As you said The idea of having a singleton class is to control the instances. As per my understanding only reason why we want to control the instances is so that we can maintain one state. Again that could be achieved with static instance variable. Could you tell me some scenario where we want to control the instances except the reason to maintain one state – M Sach Aug 26 '11 at 16:47
  • @Mohit, I am confused on how a static instance variable can achieve this? Couldn't I still create a new instance of that class and use it in my own class? The textbook example for a singleton is a database connection. You may only want one connection for your application and not allow anybody to create new instances. Creating new instances may create more connections which could be unwanted. – Amir Raminfar Aug 26 '11 at 16:50
  • Ok what i got from yoyr answer is the main purpose of singleton class is not to share the same state of object across the application but to control instance to one . But then why logger class is made singleton? – M Sach Aug 26 '11 at 17:04
  • logger is made a singleton because generally speaking you want to have one logger per class. So when you do `Logger.getLogger(getClass())` it looks for a logger that may already exist and reuse it. When instead if you had `new Logger(getClass())` you could have the same logger created multiple times if it had already been created. – Amir Raminfar Aug 26 '11 at 17:24
  • Agreed.What will be the issue if same logger created multiple times if it had already been created. Trying to get the root cause. Thanks for bearing me Amir – M Sach Aug 26 '11 at 17:36
  • @AmirRaminfar let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2901/discussion-between-mohit-gupta-and-amir-raminfar) – M Sach Aug 26 '11 at 17:39
  • @Mohit, do you still have questions about this? – Amir Raminfar Aug 29 '11 at 18:57
4

the main difference is that a singleton is a normal instance that you can for example use as a parameter. Singletons can also implement interfaces.

Matteo

Matteo
  • 14,696
  • 9
  • 68
  • 106
1

Firstly You to check your object can have muliple states(like for human states are reading,singing) or not. Then you can decide to go for Singleton Object.

Singleton provide great way to control memory footprint. In jdk Runtime class is singleton. Through Runtime.getRuntime() we get the object. Why do there need mutiple Runtime Objects. Only with One Runtime. process can be executed.

zmag
  • 7,825
  • 12
  • 32
  • 42
codingclues
  • 169
  • 2
  • 4
1

If you ever think you might want to leverage inheritance or interfaces, you'll want to use an actual instance rather than a static class. For example, what if you want to set up your instance to do something slightly different than it would normally do? You could set the singleton value to an instance of a different implementation of the interface, or to a child class that overrides certain functionality. All the code that accesses that singleton instance can use it in exactly the same way, but its behavior can be changed.

I would add, though, that both Singletons and static classes are considered an anti-pattern these days. Better to use dependency injection, and just use a singleton binding if you want singleton behavior.

public class SessionManager {
    private static final SessionManager instance;
    static {
        instance = SystemConfig.isDebug() ? new DebugSessionManager() : new SessionManager();
    }

    public static SessionManager getInstance() {
        return instance;
    }


    public int getActivePersonId() {
         // default implementation
    }
}

public class DebugSessionManager : SessionManager {
    @Override
    public int getActivePersonId() {
         // debug implementation
    }
}

// The code can be used in the same way regardless of whether we're in debug mode:
int personId = SessionManager.getInstance().getActivePersonId();

Update

After reading the question again, it sounds like you're thinking of doing something like this:

public class SessionManager {
    private static String systemName;
    public String getSystemName() {return systemName;}
}

... the assumption being that systemName will never change, and so it doesn't matter if it is accessed as new SessionManager().getSystemName() versus SessionManager.getInstance().getSystemName(). In that case:

  1. From a semantic standpoint, when another programmer sees new SessionManager(), they are expecting that something new is being created. It is not immediately obvious that every SessionManager in the system is always going to produce the same systemName. So a singleton may be preferable simply to make it more obvious to consumers that they will be dealing with a singleton state.
  2. There is a very slight overhead when you create the new SessionManager(), which must later be garbage-collected.

Other than that, you'll basically have the same advantages and drawbacks with this approach as if you used a Singleton. I'll reiterate my earlier statement, though: Singletons are an anti-pattern. Prefer dependency injection.

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • I don't think the SO is asking about static classes? If it is about static classes then I should remove my answer. I thought the questions using static variables. – Amir Raminfar Aug 26 '11 at 16:45
  • Updated based on new understanding of the question. – StriplingWarrior Aug 26 '11 at 17:33
  • It's possible to implement a singleton with an `enum` and avoid most of the problems of singleton objects in (non-enum) classes. The downside is that you can not subclass. – Andrew Lazarus Aug 26 '11 at 17:51
  • @Andrew Lazarus: I don't think implementing a singleton with an `enum` will avoid any of the problems I'm referring to: See http://accu.org/index.php/journals/337 for an idea. – StriplingWarrior Aug 26 '11 at 18:09
  • @StriplingWarrior: Two examples of traditional singleton problems avoided at the language level with enums: (1) Uniqueness under (de)serialization; (2) Non-unique construction via reflection. [Although I've heard JVM gurus can somehow construct copies of enums, it's hardly something you would see in ordinary code.] – Andrew Lazarus Aug 26 '11 at 21:44
  • Your point 1, assumes, ```new SessionManager().getSystemName()```, which can be ```SessionManager.getSystemName()``` removing semantic issue. – Nilesh Dec 21 '15 at 09:33
0

Several good answers so far.

This When is a Singleton not a Singleton article expresses the concept well.

It says:

The Singleton is a useful Design Pattern for allowing only one instance of your class, but common mistakes can inadvertently allow more than one instance to be created. In this article, I'll show you how that can happen and how to avoid it.

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.

Moreover, Singletons can be stateful; in this case, their role is to serve as a unique repository of state. If you are implementing a counter that needs to give out sequential and unique numbers (such as the machine that gives out numbers in the deli), the counter needs to be globally unique. The Singleton can hold the number and synchronize access; if later you want to hold counters in a database for persistence, you can change the private implementation of the Singleton without changing the interface.

Here are some additional differences:

  • Singletons can be stateful, but static variables cannot.
  • Singleton classes may be subclassed
rajah9
  • 11,645
  • 5
  • 44
  • 57