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.

Similar Messages

  • 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

  • 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 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....

  • 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.

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Singleton bottleneck with static methods?

    A discussion came up at work today. If a class is created as a Singleton and only provides static methods and only final static data members (just for storing read only info like a connection string), will this create a bottleneck? Someone was suggesting that sharing the Singleton would cause each thread accessing the code to have to obtain the monitor on the class before being able to execute the method. Is this the case? None of the methods are synchronized, but they all perform atomic functionality. Anyone have any input on this?

    Currenlty, it is implemented as a Singleton, part of
    the discussion was moving everything into static
    methods. Aside from that, the question is still
    whether having a single location to run methods from
    will become a bottleneckWho came up with the idea that this would create some sort of bottleneck? Never pay attention to them again.
    Static methods are (slightly) faster than ordinary instance methods because there is no virtual method lookup. The only way there would be some sort of performance implication is if the methods are synchronized. In that case performance will be essentially the same as synchronized instance methods of a singleton.

  • What's the differences between a singleton and a class with static methods

    Hi everybody.
    My question is in the subject. Perhaps "differences" is not the good word. The positive and negative points ?
    Imagine you have to write a connection pool, sure you gonna choose a singleton but why ?
    Thank you very much.

    A class is a class. Java doesn't have (and I wish it
    did) a static outer class. Any class can extend
    another class or implement an interface.A Class object cannot extend or implement anything - it is not under programmer control in any way. You can create a class which implements interfaces, but calling static methods is completely unrelated. Interfaces only affect instance methods, not class ones. I think all of your comparison to C++ is actually confusing you more. In Java, there is a real class object at runtime, as opposed to C++.
    YATArchivist makes a good point about being able to
    serialize, altho I've not met that desire in practice.
    Maybe a concrete example would help.
    mattbunch makes another point that I don't understand.
    A class can implement an interface whether it sticks
    its data in statics or in a dobject, so I guess I
    still don't get that one.See my comment above. Static methods are free from all contractual obligations.
    I prefer instance singletons to singleton classes because they are more flexible to change. For instance I created a thread pool singleton which worked by passing the instance around, but later I needed two thread pools so I made a slight modification to the class and poof! no more singleton and 99% of my code compiled cleanly against it.
    When possible, I prefer to hand the instance off from object to object rather than have everything call Singleton.instance() since it makes changes like I mentioned earlier more feasible.

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

  • JNI static method call fails for the 6th time

    Hello,
    I have a JNI Method which calls the static method which gets reference to singleton class(getReference()), JVM crashes.
    what might be the problem?
    is it due to insufficient memory or any other reason?
    Here is my code.
    eScannerClass = gEnv->FindClass("com/elvista/jscaner/EScanner");
    eScannerContructId = gEnv->GetStaticMethodID(eScannerClass,"getReference","()Lcom/elvista/jscaner/EScanner;");
    eScannerUpdateMethodId = gEnv->GetMethodID(eScannerClass,"updateScanStatus","(Lcom/elvista/jscaner/EScanEvent;)V");
    eScannerObjectRef = gEnv->NewObject(eScannerClass,eScannerContructId);Thanx for any help on this.

    Hi,
    the eScannerContructId is refering a static method, not a constructor. Therefore you must not use gEnv->NewObject, which is only allowed for constructors. Instead you have to use gEnv->CallStaticObjectMethod to call getReference().
    Martin

  • Re: static methods in an interface?

    You cannot define a constructor in an interface, (part of the language specification), and static methods belong to the class so how could a derived concrete class possibly implement something that belonged to its ancestor abstract class? Look at the factory pattern & perhaps Singleton for more guidance and seriously consider why you're attempting to do this. In fact, post the reasoning behind this decision and see if there are any useful comments / suggestions on that.

    This certainly sounds like a candidate for the Factory pattern, (or one of its specialisations such as Flyweight). Check out the forum here or one of the many sites focused on this area. You'll see that you're trying to solve a common problem in an unnecessarily complex way.

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • 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.

  • Interesting Qtion: Synchronize a static method

    I know that a non-static method and a block can be synchronized.
    Can anyone tell me as to what it means to synchronize a static method of a class and how/when is it used. I just tried compiling the code and it gives no compiler/syntactical errors.
    it would be helpful if u could take up a simple class example.
    Thanks,
    Novice

    Hi,
    A good example for using synchronized static methods is the singleton pattern. E.g.
    public class Singleton
      private Singleton() {}
      private static Singleton fgUniqueInstance;
      public static synchronized Singleton getInstance()
        if (fgUniqueInstance==null) {
          fgUniqueInstance = new Singleton();
        return fgUniqueInstance;
    }If you won't synchronize this class in a multi-threading environment, it could happen, that more than one instance is created.
    Andre

Maybe you are looking for