开发者

When we should go for a Singleton class in Java?

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?


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.


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


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.


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.


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜