简体   繁体   中英

Singleton Vs static variable

I need to use a global counter in my application which increments count for every request made. I am going to put this counter in a separate class something like this:

public class Counter{  
  private static int count = 0;  
  public synchronized static update()
  {
    count += 1;
  }  

  public synchronized static int getCount()
  {
    return count;
  }  
}

There exists only one Counter throughout the lifetime of the application. Do I get any benefit by making it a singleton since there is a single one? Does it make more sense to create a single instance instead of having a class with static variables? What would be the benefit

I would make it either static (field and methods) or not. You appear to have a combination which is bound to confuse.


In this case, I would just use an AtomicInteger :

public enum Counter {
    public static final AtomicInteger COUNTER = new AtomicInteger();
}

so that you can do

import static Counter.COUNTER;

int num = COUNTER.incrementAndGet();

I don't see any need to make it a singleton or static. Instantiate a new Counter in a logical spot (instance variable of a class that's generating the requests?) and use it from there. That way, the Counter class is still reusable elsewhere if you need it and you don't have to worry about anyone else grabbing and updating your counter...

It is more common to use singleton when the class has state (it has fields). When the class is stateless - it is a utility class and usually its methods are static.

Did not see that this is a question tagged with Java and not C++; Anyways I will leave it here unless someone wants this removed.

The thing about static class members is that they are closely coupled with a class rather than an class instance. In other words there is only one memory allocation for the static variable, that will be shared among all the instances of this class (class objects).

In your code above, in the getCount() method, you

return this.count;

Remember that static members do not have this pointer, meaning they are to be accessed using classname::static_member when accessing from outside of the class, and use just the variable name when defining class methods, like you did above. So your code should look similar to:

return count;

If you want only one copy of the class members, for any number of class objects created, then you are better off with static methods and - static methods can only operate with static members.

If you do not like static methods and static members, singleton is not a bad approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM