David Graham wrote:

Static methods are evil for many reasons including philosophical (they're
not OO) and practical (you can't override their behavior).  You should use
a Singleton class with non-static methods.

And the generally accepted way to get a reference to the singleton is with a static "getInstance" method, right? Is there any way to make an anonymous subclass of a Singleton that uses a static method to get the instance? For example:



public class SubclassSingleton {


  public static void main(String[] args) {
    MySingleton ms = new MySingleton() {
      int doSomething() {
        return 42;
      }
    }

    MySingleton inst = ms.getInstance();
    System.out.println(ms.doSomething());
  }
}

class MySingleton {

static MySingleton me;

  static getInstance() {
    if (MySingleton.me == null)
      MySingleton.me = new MySingleton();

    return MySingleton.me;
  }

  int doSomething() {
    return 8;
  }
}



This simple code doesn't work, because even if you subclass the singleton and override one of the methods, the getInstance() method will create a base-class MySingleton. And since this method is static, it can't be overridden. So while singletons are useful, you can't use them in anonymous subclasses (as far as I can tell), which makes them difficult to use with mock object unit testing.

Please someone point out the flaw in my reasoning, it has bothered me for quite a while and I'd love to be proven wrong.



Erik


--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to