Singleton vs. Static

I'm developing an application and I have read a number of articles on the use of a Singleton vs. a static class (a class with all static members).
From my perspective, it seems that it's best to use static classes when you have pure, stateless functions. Singletons should be used when the information being held represents the state of an object (a single object, but an object nonetheless).
I may be opening a can of worms here, but as I am developing an API for other developers to use, I am really trying to make sure I do this right because, once it's in place and in use, it won't be something that is easily changeable in the future.
Thanks for any help!

JavaDevGuy wrote:
I'm developing an application and I have read a number of articles on the use of a Singleton vs. a static class (a class with all static members).
Seems like a way to compare apples and oranges.
From my perspective, it seems that it's best to use static classes when you have pure, stateless functions. Singletons should be used when the information being held represents the state of an object (a single object, but an object nonetheless).
First we start by recognizing that singleton is a conceptual entity which represents an object. Objects have behavior and state.
Then we look at implementing a singleton. One can implement a singleton using the standard pattern (from GoF) or one can use an entirely static front end. That is an implementation detail which does not change anything about whether it is singleton or not (although it can, very rarely, limit desired functionality.)
Conversely one might also use a static class as a collection of related behaviors. Behaviors with no data are not objects. Thus, for example, java.lang.Math. That is not and never can be deemed a singleton.
I may be opening a can of worms here, but as I am developing an API for other developers to use, I am really trying to make sure I do this right because, once it's in place and in use, it won't be something that is easily changeable in the future.Are you delivering a library or is this just part of of a another deliverable?
The distinction is important. The Java API is a library which is delivered independent of the applications that use it. It has its own delivery schedule and a complete set of independent unit tests (with absolutely no dependency on applications).
Conversely for an application that uses a database layer the database layer is not a library. It might be referred to that but its existence is tied to the application. It is delivered with the application and its schedule is always tied to it. And unit tests might exist that test functionality that either is known or discovered about the application rather than specifically about the layer.
Deciding on the difference between the two impacts the design and architecture perspective that one must take.

Similar Messages

  • Singleton vs static - which is better?

    Of the two approaches -
    a class which can be used by accessing its ONLY instance(singleton) or a class which has a set of static methods which can be invoked on the class itself
    which is better and why? Or are these just two 'styles' of programming?
    I always get confused as to which way to go? I tend to prefer to have static methods on the class instead of a singleton.
    All insights/comments/ideas welcome.
    Thanks

    Well, there are a few questions you can ask - does the method cause any changes of state, or is it a pure function? If the latter, static is probably the way to go.
    The way you are talking, I gather that there is some state involved.
    Next question: does it make sense for there to be more than one of these per JVM? Not only in the way you currently envision it, but at all, anywhere. For example, consider the list of Strings that the String class keeps so it can consolidate memory and avoid duplication (see String.intern() ). That list makes sense to be static.
    On the other hand, the representation of the state of a board game should not be static, because someone could want to write a program which has multiple games within it - or you could within one game wish to have contingencies or undo-ability (essentially, it might not be as singleton as you think).
    Next, if you think the methods will ever need to be overridden, use a singleton, because static methods aren't, well, dynamic! (in case the singleton is a one-at-a-time singleton but it makes sense to have a change of identity over time).
    I have never written a true singleton - though often written classes which I did not PLAN on instantiating more than once.

  • Singleton or static methods for DAO?

    Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?

    A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
    This is not possible with static methods- you would have to change the client code to use a different data source.
    There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
    Pete

  • Design Pattern: Is the Universe Object a Singleton or Static or either way.

    Hi All,
    1. I've read this thread: static versus singleton
    http://forum.java.sun.com/thread.jsp?forum=425&thread=401035&tstart=105&trange=15
    2. Now, specifically if you were to model the Universe Object, what would you choose? a Singleton
    or a Static Class or either way depending on your design point of view?
    (either way depending on your design point of view imply there is more than one solution to a problem.)
    Basically, I'm looking for is the justification of one (singleton) or the other (static) or doesn't matter
    in addition to the pure technical pros and cons (or avantage/disavantage) of singleton versus Static (see pt. 1)

    <dubwai>
    What's 'the Universe Object'?
    </dubwai>
    Sorry, for not being clear. My assumption is that every body would undertand the word 'Universe' immediately. So with this clarification. I hope you will have more input. Thanks.
    public class Universe //Singleton
         private static Universe instance = new Universe(); 
         private Universe()
         public static Universe getInstance() 
           return instance;
         public void do() 
    public class Universe  //Static Class like Math class for example
         public static void do() 
         ...all other methods are static
    <os>
    Personally, I'd make the universe a singleton.
    The universe is an 'object', not a class, and if alternate universes are proved to exist you can create new instances,
    and not treat it as a singleton any more, without much rewriting (a static implementation would need a total rewrite).
    </0s>
    1. Keywords: Personally and alternate universes are proved to exist.
    Yes, this is the kind of reasoning I'm looking for. By that I mean when we design a class, our reasonning should not depends
    on the 'pure' technical concepts of what Singleton class or Static class can do but rather depending on the reality
    of the world. And then from that understanding we would choose a Singleton or Static class. This is what I meant by 'Either way, it doesn't matter' which depend on one's view about of existence of the universe whether it's unique or not. In your case (Os), you prefer Singleton because of the possibility of alternate universes.
    2. Now, let's admit, there is only one Universe, would you still prefer Singleton class over Static class? for all the techincal reasons that you said
    "As a singleton,..."
    "It would also probably be useful to treat the universe as a generic Object..."
    OR just because a Singleton would be 'safer' to cover the possibility of design extension in that can cover all cases (alternate as well)

  • Singleton Vs Static Class

    Hi,
    Kindly excuse if my question annoys anyone in the forum.
    Compared to a singleton class we can always have a class and all methods as static?
    Wouldnt that be the same as Singleton.
    Also looking at Runtime class, its a Singleton. Just thinking if Runtime class could be a class with this static methods instead of making the constructor private .

    I thought I read somewhere that however you implement your singletons, client code shouldn't break if later you decide that you don't need/want a singleton for that class anymore.I agree with that principle.
    This requires that the client code never calls the getInstance() method, and the best way to make sure of that is that the client code does not depend on the singleton class, but on an interface that the singleton class implements.
    (Speaking for myself, I can assure you that I never thought that deeply about it, but continuing...)I have thought a lot about Singletons, specifically when contemplating flaying myself alive for putting them prematurely where they weren't really needed (not to mention some of my colleagues' choice, for fear my message would deserve editing out by moderators).
    I have come to the conclusion that Singleton is overhyped, probably because it's one of the simplest patterns, and the first one people are taught as a way to illustrate the very concept of "design pattern". And overused because it feels so natural to use the first and simplest pattern one has learnt.
    I'm not claiming Singleton has no merits (I used to claim that on this forums). I'm claiming most usages I've seen of Singleton were not based on a careful consideration of the real merits.
    If we implement our singletons (who have state) as "static classes", aren't we violating this?Ah, OK, I get it now: if someday you need to have several copies of the states with different values, you could always "de-singletonize" the singleton, with minimal impact for properly-written client-code, as you point out, whereas you couldn't justas easily "de-staticize" the static calls.
    Indeed that's an argument when evaluating whether making a method static: it statically (1) binds the client code to the implementation class.
    (1) not a pun, merely the very justification for the term static as a keyword.
    J.

  • Singleton Versus Static method

    Can some body explain me advantange of making a class single ton over making all attribute and Operation static? I know Single ton means user can create only instance of the object. Can't same functionality be achieved by making all attributes and operations in class static and making constructor private to prevent them from making instance?

    I know Single ton means user can create only
    instance of the object.You can use more than one instance in singleton pattern if you want. But, in this case, the name "singleton" wouldn�t be appropriate.
    In most of cases only one instance is used in singleton. It is more usual. But you can use more than one instance, limiting the number of active instances of your singleton. You can achieve this using an array that will contain instances of this singleton. You can set this array with an amount of elements that corresponds with the maximum amount of instances of this singleton.
    I don�t know preciselly if the performance of the application is better when you define, for example, 5 instances of your singleton at the most, rather than only one instance. I just mention this because I�ve already seen something like this. Maybe it improves the performance, I don�t know....

  • Singletons and Static class behavior

    Hi all and thanks for taking a look at this,
    I was playing around with a Singleton class today and it raised raised a few questions around Static methods in the singleton. When my class is instatiated I load some data into a HashMap map that I want to make available for read only purposes through other methods in my singleton.
    I really wanted to just call a static method to look up the value, so I followed the standard model. I had a private static HashMap that is loaded with data when the Contructor is called from the getInstance(). I included the standard model example for you if you wanted to refer to it.
    I ran my code making a static MyClass.getData() call to see what would happen. The static call did not return a value, I wasn't surprised. Then I added a call to MyClass.getInstance() followed by the static MyClass.getData() call and this returned the appropriate value.
    Then I changed my Singleton as follows and was wondering if there were any issues that might result because of this and I was wondering what the process that is followed by java when calling a static method (what does it use, where does it look).
    My Code:
    public class MyClass {
    private static MyClass instance;
    private static HashMap myData;
    private MyClass() {
    myData = new HashMap();
    myData.put("1", "value 1");
    myData.put("2", "value 2");
    private static synchronized void getInstance() {
    if (instance == null)
    instance = new MyClass();
    public static String getData(String key) {
    if (myData == null)
    getInstance();
    return (String)myData.get(key);
    The standard singleton model class:
    public class MyClass {
    private static MyClass instance;
    private MyClass() { }
    public static synchronized MyClass getInstance() {
    if (instance == null)
    instance = new MyClass();
    return instance;
    ... rest of methods (not static)
    }

    Thanks for the reply,
    Really my only reason for making it static was so the calling class would not have to get a handle to the actual MyClass Instance. Therefore avoiding the Synchronization method.
    I was attempting to aviod the famous broken double check locking by having the checks in different methods. I am assuming from you warning that keeping the methods seperate and synchronizing the getInstance is really no different than putting a synchronize(this) block around the second check and the constructor call?
    Really my objective is to retrive data once, not really create a single access point for getting the data. As an alternative, I tried the following code and it seems to work, any issues you can see with this?
    public class MyClass {
    private static HashMap hm;
    static {
    hm = new HashMap();
    // code to get Data into HashMap
    public static String getData(String key) {
    return hm.get(key);

  • Singleton Vs Static Classes

    What is the Difference b/w implementing a singleton pattern and
    making a class Static?

    If you implement a (the?) singleton pattern, references to the resulting
    object can be passed around as method arguments, and it can
    belong to a class which implements useful interfaces or extends
    some useful base class.

  • Singleton without Static Methods

    Hi all,
    Is there a way to make a Singleton without using static methods?
    I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
    Any ideas?

    mycoffee wrote:
    gcameo wrote:
    Hi all,
    Is there a way to make a Singleton without using static methods?
    I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
    Any ideas?Another way. In the class, create a static (still static) variable instanceCount
    Write a close() method and call it whenever you are done with the class
    then if the contructor is called, add 1 to the count. in the close() substract 1 from teh count
    If the contructor is called when the count = 1 throw new Exception("I want to be alone"); LOLOuch, sounds like the worst solution so far.

  • Singleton with static members only

    If I have a singleton class with static members only and I'd like to ensure that nobody accidentally instantiates the class, would it make sense to declare the class abstract? Or instead should I leave it non-abstract but make the no-argument constructor private? Or both?
    Which of these approaches would you recommend?
    Thanks.

    pros of using classical singletons (per Head First
    Design Patterns):
    1) It ensures that one and only one object is
    instantiated for a given class.This is effectively the same as using a non-instantiable class with all static members. You don't have an instance, but you have exactly one of it.
    2) It gives a global point of access like a global
    variableAgain, same thing with a non-instantiable class with all static members.
    3) It is only created when you need it (unlike a
    global variable) and thus wastes no resources if it
    is not needed.Again, same thing.
    Also, Java does not have global variables.
    Also, no variable in Java requires more than 8 bytes, and most are 4 or 2.
    4) Using a static self-contained class in place of a
    singleton can be a source of subtle, hard-to-find
    bugs often involving order of initialization of
    static code.Eh? Example please?
    5) Global variables encourage developers to pollute
    the namespace with lots of global references to small
    objects.What global variable? Java doesn't have global variables? How is a class full of statics any more a global than a "real" singleton?

  • SingleTon Vs static methods

    Which one of the is better?
    class with all static methods
    (or)
    single ton class
    Regards,
    Govind

    Singleton is a design pattern used to ensure that only one instance of a class can ever exist. A static method is not a design pattern it just makes it possible to call this method on a class without ever having to have created an instance of the class. In fact it has nothing to do with the instance. there could be none or 20 instances.

  • Static vs Singleton for cache

    Hi!
    I'm developing a web application, where I want to cache some Java objects in a HashMap. The Objects will then be fetched using something like this:
    Cache.getPost(String key);
    But I'm not sure if I can use a static method and a static HashMap for this? Is a Singleton more suited? If so, why?
    Vidar

    Allow me to elaborate...
    Using a static hashmap and a static method, there will >only be one 'instance' of the hashmap, shared between >the different instances of the class, right?Yes, if you choose to instantiate instances of the class that contains the static hashmap. Typically when you have a situation like what you are describing you don't need to create instances of the class containing the map itself - just provide methods to get/put data in and out of the map. Here is a quick example:
    public class Cache {
    private static Map cacheMap = new HashMap();
    public static void set(Object key, Object value) {
    cacheMap.put(key, value);
    public static void get(Object key) {
    cacheMap.get(key);
    The Singleton only has one copy(usually) of the >hashmap as well, because there will only be one >instance of the class itself.That is correct. The only difference from the above example is the fact that you will declare the Map as an instance attribute, and not a static attribute.
    My plan is to fill the cache with objects created with >data from my database at startup, and check the >database every 10 minutes to see if there has been any >changes. If there has, the cache will be updated to >reflect this.Not a problem - the "static" example above will work just fine, as will a Singleton solution. What you have to watch out for is thread concurrency issues. For example, let's say that I go to the cache at the exact same instant that a daemon thread is updating data from the database. You can't guarantee that your cache request will be the old or new value without handling thread locking issues. There is really not enough space here to give this the attention it deserves. I'd recommend that you take a look at the threading forum and see if there are any cache updating examples posted over there...
    Will both a singleton and static solution be capable >of doing this?Yes. Both are capable, and it boils down to a matter of choice more than anything else. The big issue you need to address is how to handle the updating process.
    Jonathan House

  • Can a object created using static keyword be recreated? Singleton Pattern

    Hi All
    To implement a Singleton I can use the following code
    public Singleton {
    private Singleton(){
    private static final s_instance = new Singleton();
    public Singleton getInstance(){
    return s_instance;
    Now if the Class Singleton gets unloaded during a program execution and again get loaded won't s_instance be recreated? If my question is correct this would lead to be leading to a new Singleton class instance with all the original variables.
    Having answered the above question if I lazily initialize my Singleton using the following code won't the above problem still occur.
    public Singleton {
    private Singleton(){}
    private final volatile Singleton s_instance = null;
    public Singleton () {
    if(s_instance != null) {
    synchronized (s_instance) {
    s_instance = new Singleton();
    return s_instance;
    Having answered all the above questions what is the best way to write a Singleton?

    Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
    On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
    To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
    *2.17.8 Unloading of Classes and Interfaces*
    A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
    Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
    The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
    Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

  • Static or singleton for clipboard handling

    Hi Everyone,
    I have the below class with static methods for handling the system clipboard in my small application. I've read that when there is a state maintained I should prefer singleton over static methods. So I guess, I should make this class a singleton because of the Clipboard object in it.
    Could someone maybe explain it a little bit what is behind this advice and why would it be better in this case ? What situation can occur when these static methods are not good but the singleton would be?
    I suppose these methods won't need to be polymorphic in the future, so that's probably not a factor.
    Thanks for any comments in advance,
    lemonboston
    public class ClipboardAction {
         private static Clipboard clipboard;
         static {
              clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
         public static String getText() {
              try {
                   Transferable trans = clipboard.getContents(null);
                   return (String) trans.getTransferData(DataFlavor.stringFlavor);
              } catch (UnsupportedFlavorException e) {
                   JOptionPane.showMessageDialog(null,
                             "Not text on Clipboard. Try again.");
                   return "";
              } catch (IOException e) {
                   JOptionPane.showMessageDialog(null,
                                       "Something happened when trying to access clipboard. (IOException)\nTry again.");
                   return "";
         public static void clear(){
              StringSelection data = new StringSelection("");
              clipboard.setContents(data, null);
         public static void setText(String text){
              StringSelection data = new StringSelection(text);
              clipboard.setContents(data, null);
    }

    Thank you guys for the comments. So what is the solution now? :)
    If I understand it correctly there is one vote for static, one for singleton and one for none.
    EJP, do you mean that there is no need to keep a clipboard reference variable? So instead of this in my class:
    private static Clipboard clipboard;
         static {
              clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
         }I could use this?:
    private static Clipboard clipboard(){
              return Toolkit.getDefaultToolkit().getSystemClipboard();
         }I don't know what is 'cache' exactly but isn't this system Clipboard (singleton) object there anyway, and I just create a reference for it, which I guess doesn't take too much system resource? Based on this I don't see a big difference in solutions above.
    Or did you mean something else? (probably.. :) )
    Thanks in advance for any further help with this.

  • Difference between a static class and singleton

    What is the difference between a static object and a singleton ?
    for example:
    1 )
    public class MyObject {
    static MyObject singleton ;
    public static MyObject getInstance() {
    if (singleton ==null) singleton = new MyObject ();
    return singleton;
    private MyObject () {
    supe();
    public void myMethod() {
    2 )
    public class MyObject {
    private MyObject () {
    supe();
    public static void myMethod() {
    If I need to call the myMethod() , witch of this solution is better ?
    // case 1
    MyObject.getInstance().myMethod()
    // case 2
    MyObject.myMethod()
    .....

    This has been discussed a lot here.
    Use the forum's search feature, or, since it's not necessarily reliable, use google.
    For many intents and purposes, they're equivalent.
    However, with a singleton you can implement an interface, and get polymorphic behavior. You can't do with with a class full of static methods (which, by the way, is NOT a static class).

  • Why the singleton pattern used rather than static things?

    class Single
        private Single() {}
        private void print() { System.out.println("Foo~"); }
        private static Single one = new Single();
        public static void print() { one.print(); }
    class Stat
        public static void print() { System.out.println("Foo~"); }
    }What's the different?? What is the benefit of the singleton one?

    There is no practical difference - because, in fact, that is not the singleton pattern!
    A singleton would look like:
    class Singleton {
        private Singleton() {}
        public void print() { System.out.println("Foo~"); }
        private static Singleton instance = new Singleton();
        public static Singleton getInstance() { return instance; }
    }The benefit of this pattern is, that your client code doesn't have to know that there is only one instance (getInstance could return another instance for every call) or of which actual type it is (getInstance could return an instance of any Subclass of Singleton).
    See http://c2.com/cgi/wiki?SingletonPattern for more information on the pattern.

Maybe you are looking for