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.

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

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

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

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • 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

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

  • Calling a method from a static method

    hello all,
    I'm calling a non-static method from a static method (from the main method). To overcome this i can make the method i am calling static but is there another way to get this to work without making the method that is being called static?
    all replies welcome, thanks

    When you call a non-static method, you are saying you are calling a method on an object. The object is an instance of the class in which the method is defined. It is a non-static method, because the instance holds data in it's instance variables that is needed to perform the method. Therefore to call this kind of method, you need to get (or create an instance of the class. Assuming the two methods are in the same class, you could do
    public class Foo
         public static void main(String[] args)
                Foo f = new Foo();
                f.callNonStaticMethod();
    }for instance.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Dynamic call of a static method of an static attribute

    Hi all,
    is it possible to call dynamically a static method of a static attribute of a class.
    The statement without dynamic call would look like this:
    cl_test_class=>static_attribute=>static_method( ).
    I would like to do it like this:
    ('CL_TEST_CLASS')=>static_attribute=>static_method( ).
    Netiher the one nor the other way works for me - I'm getting the error "The notation used is reserved for business object classes".
    Regards, Stefan

    I guess, it is not possible to call method using the short form (parameters in brackets) is not possible in Dynamic Access. You may need to get the attribute first and then call the method.
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: o_same TYPE REF TO lcl_main.
        METHODS: run.
    ENDCLASS.                    "lcl_main DEFINITION
    CLASS lcl_main IMPLEMENTATION.
      METHOD run.
        WRITE: 'success'.
      ENDMETHOD.                    "run
    ENDCLASS.                    "lcl_main IMPLEMENTATION
    START-OF-SELECTION.
      DATA: lo_same TYPE REF TO lcl_main.
      CREATE OBJECT lcl_main=>o_same.
    *  lcl_main=>o_same=>run( ).
      TRY.
          FIELD-SYMBOLS: <fs> TYPE REF TO lcl_main.
          ASSIGN ('LCL_MAIN')=>('O_SAME') TO <fs>.
          CALL METHOD <fs>->('RUN').
        CATCH cx_root.
      ENDTRY.
    Regards,
    Naimesh Patel

Maybe you are looking for

  • Why doesn't my print-out look like the screen view?

    This happens every time I use Firefox. Whenever I try to print a listing from Ebay, the main picture is omitted from the print-out. Here is an example. This first link is to a screen-shot (Fn and PrtSc) of a typical listing on Ebay: http://s1176.phot

  • Testjava.lang.NullPointerException

    Hi everybody, Regarding the above error message, could anybody give me an idea what could have cause the problem? When i compile my JSP and servlet files, it doesn't show any build error. Message appears after i run the file. Any Idea or advice? erro

  • Toc file name

    what is the toc file name for X5? and where can I find it?

  • Servicegen XML beans

    Is there any good example of using Weblogic web services with XML beans, but without using BEA's workshoop ? I've seen that the workshoop is able to handle web service + xml beans, but I haven't found the way to do it outside it. another question: is

  • Vision demo or fresh databse?

    I am a student using E-business suite R12, i have sucessfully installed the E-business suite with vision demo database on my machine.my project is related to four modules HRM, Finance, Inventory Management and Project Management, so should i use visi