struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David Graham <grahamdavid1...@yahoo.com>
Subject Re: [OT] Use of Static Methods
Date Wed, 09 Jul 2003 16:59:23 GMT
--- Erik Price <eprice@ptc.com> wrote:
> 
> 
> 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?  

Yep, that's the one use case that I accept the use of static methods :-).

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

The AbstractFactory and FactoryMethod patterns are applicable in this
situation.

David

> 
> 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: struts-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: struts-user-help@jakarta.apache.org
> 


__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com

---------------------------------------------------------------------
To unsubscribe, e-mail: struts-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: struts-user-help@jakarta.apache.org


Mime
View raw message