When we should go for a Singleton class in Java?

2020-02-26 10:39发布

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?

5条回答
劳资没心,怎么记你
2楼-- · 2020-02-26 10:47

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.

查看更多
贼婆χ
3楼-- · 2020-02-26 10:50

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

查看更多
做自己的国王
4楼-- · 2020-02-26 11:00

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.

查看更多
我命由我不由天
5楼-- · 2020-02-26 11:04

Several good answers so far.

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

Here are some additional differences:

  • Singletons can be stateful, but static variables cannot.
  • Singleton classes may be subclassed
查看更多
够拽才男人
6楼-- · 2020-02-26 11:08

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.

查看更多
登录 后发表回答