**** DISCLAIMER ****

"This e-mail and any attachment thereto may contain information which is confidential 
and/or protected by intellectual property rights and are intended for the sole use of 
the recipient(s) named above. 
Any use of the information contained herein (including, but not limited to, total or 
partial reproduction, communication or distribution in any form) by other persons than 
the designated recipient(s) is prohibited. 
If you have received this e-mail in error, please notify the sender either by 
telephone or by e-mail and delete the material from any computer".

Thank you for your cooperation.

For further information about Proximus mobile phone services please see our website at 
http://www.proximus.be or refer to any Proximus agent.
+1

But can you make some comments on the following critics about Singletons I'm reading 
from

http://www.theserverside.com/resources/articles/RodJohnsonInterview/JohnsonChapter4.pdf

Thx,

José.


[from page 139]

Avoid a Proliferation of Singletons by Using an Application Registry

The Singleton design pattern is widely useful, but the obvious implementation can be 
dangerous. The obvious way to implement a singleton is Java is to use a static 
instance variable containing the singleton instance, a public static method to return 
the singleton instance, and provide a private constructor to prevent instantiation:

public class MySingleton {

/** Singleton instance */
private static MySingleton instance;

// Static block to instantiate the singleton in a threadsafe way static { instance = 
new MySingleton(); } // static initializer

/** Enforces singleton method. Returns the instance of this object.
* @throws DataImportationException if there was an internal error
* creating the singleton
* @return the singleton instance of this class
*/
public static MySingleton getInstance() {
return instance;
}

/** Private constructor to enforce singleton design pattern.
*/
private MySingleton() {
...
}
// Business methods on instance

Note the use of a static initializer to initialize the singleton instance when the 
class is loaded. This prevents race conditions possible if the singleton is 
instantiated in the getInstance() method if it's null (a common cause of errors). It's 
also possible for the static initializer to catch any exceptions thrown by the 
singleton's constructor, which can be rethrown in the getInstance() method. However, 
this common idiom leads to several problems:

❑ Dependence on the singleton class is hard-coded into many other classes.

❑ The singleton must handle its own configuration. As other classes are locked out 
of its initialization process, the singleton will be responsible for any properties 
loading required.

❑ Complex applications can have many singletons. Each might handle its configuration 
loading differently, meaning there's no central repository for configuration.

❑ Singletons are interface-unfriendly. This is a very bad thing. There's little 
point in making a singleton implement an interface, because there's then no way of 
preventing there being other implementations of that interface. The usual 
implementation of a singleton defines a type in a class, not an interface.

❑ Singletons aren't amenable to inheritance, because we need to code to a specific 
class, and because Java doesn't permit the overriding of static methods such as 
getInstance().

❑ It's impossible to update the state of singletons at runtime consistently. Any 
updates may be performed haphazardly in individual Singleton or factory classes. 
There's no way to refresh the state of all singletons in an application.

A slightly more sophisticated approach is to use a factory, which may use different 
implementation classes for the singleton. However, this only solves some of these 
problems.

I don't much like static variables in general. They break OO by introducing dependency 
on a specific class. The usual implementation of the Singleton design pattern exhibits 
this problem.

In my view, it's a much better solution to have one object that can be used to locate 
other objects. I call this an application context object, although I've also seen it 
termed a "registry" or "application toolbox". Any object in the application needs only 
to get a reference to the single instance of the context object to retrieve the single 
instances of any application object. Objects are normally retrieved by name. This 
context object doesn't even need to be a singleton. For example, it's possible to use 
the Servlet API to place the context in a web application's ServletContext, or we can 
bind the context object in JNDI and access it using standard application server 
functionality. Such approaches don't require code changes to the context object 
itself, just a little bootstrap code.

The context object itself will be generic framework code, reusable between multiple 
applications.

The advantages of this approach include:

❑ It works well with interfaces. Objects that need the "singletons" never need to 
know their implementing class.

❑ All objects are normal Java classes, and can use inheritance normally. There are 
no static variables.

❑ Configuration is handled outside the classes in question, and entirely by 
framework code. The context object is responsible for instantiating and configuring 
individual singletons. This means that configuration outside Java code (such as an XML 
document or even RDBMS tables) can be used to source configuration data. Individual 
objects can be configured using JavaBean properties. Such configuration can include 
the creation of object graphs amongst managed objects by the application context, 
without the objects in question needing to do anything except expose bean properties.

❑ The context object will implement an interface. This allows different 
implementations to take configuration from different sources without any need to 
change code in managed application objects.

❑ It's possible to support dynamic state changes to "singletons". The context can be 
refreshed, changing the state of the objects it manages (although of course there are 
thread safety issues to consider).

❑ Using a context object opens other possibilities. For example, the context may 
provide other services, such as implementing the Prototype design pattern to serve as 
a factory for independent object instances. Since many application objects have access 
to it, the context object may serve as an event publisher, in the Observer design 
pattern.

❑ While the Singleton design pattern is inflexible, we can choose to have multiple 
application context objects if this is useful (the infrastructure discussed in Chapter 
11 supports hierarchical context objects).

The following code fragments illustrate the use of this approach. The context object 
itself will be responsible for loading configuration. The context object may register 
itself (for example with the ServletContext of a web application, or JNDI) or a 
separate bootstrap class may handle this. Objects needing to use "singletons" must 
look up the context object in. For example:

ApplicationContext application = (ApplicationContext ) 
servletContext.getAttribute("com.mycompany.context.ApplicationContext");

The ApplicationContext instance can be used to obtain any "singleton":

MySingleton mySingleton = (MySingleton ) 
applicationContext.getSingleInstance("mysingleton");

In Chapter 11 we'll look at how to implement this superior alternative to the 
Singleton design pattern. Note that it isn't limited to managing "singletons": this is 
valuable piece of infrastructure that can be used in many ways.

Why not use JNDI – a standard J2EE service – instead of use additional 
infrastructure to achieve this result? Each "singleton" could be bound to the JNDI 
context, allowing other components running in the application server to look them up.

Using JNDI adds complexity (JNDI lookups are verbose) and is significantly less 
powerful than the application context mechanism described above. For example, each 
"singleton" would be left on its own to handle its configuration, as JNDI offers only 
a lookup mechanism, not a means of externalizing configuration. Another serious 
objection is that this approach would be wholly dependent on application server 
services, making testing outside an application server unnecessarily difficult. 
Finally, some kind of bootstrap service would be required to bind the objects into 
JNDI, meaning that we'd probably need to implement most of the code in the application 
context approach anyway. Using an application context, we can choose to bind 
individual objects with JNDI if it proves useful.

Avoid a proliferation of singletons, each with a static getInstance() method. Using a 
factory to return each singleton is better, but still inflexible. Instead, use a 
single "application context" object or registry that returns a single instance of each 
class. The generic application context implementation will normally (but not 
necessarily) be based on the use of reflection, and should take care of configuring 
the object instances it manages. This has the advantage that application objects need 
only expose bean properties for configuration, and never need to look up configuration 
sources such as properties files.


-----Original Message-----
From: Craig R. McClanahan [mailto:[EMAIL PROTECTED] 
Sent: Thursday, July 10, 2003 10:42 AM
To: Struts Users Mailing List
Subject: Re: [OT] Use of Static Methods




On Thu, 10 Jul 2003, Simon Kelly wrote:

> Date: Thu, 10 Jul 2003 09:56:14 +0200
> From: Simon Kelly <[EMAIL PROTECTED]>
> Reply-To: Struts Users Mailing List <[EMAIL PROTECTED]>
> To: Struts Users Mailing List <[EMAIL PROTECTED]>
> Subject: Re: [OT] Use of Static Methods
>
> I'm gonna get shot down in flames here, but I feel this may be a good 
> way of looking at the differences between static and non-static 
> methods.

A lot of the discussions in this thread have been about philosophy -- let's also take 
a look at a use case that is more practical to Struts oriented developers and use that 
to compare the two approaches.

Many of you will be aware that Struts uses BeanUtils.populate() -- which, in Struts 
1.1, references a static method on the BeanUtils class from version 1.6.1 of BeanUtils 
-- that performs the copy+convert loop. It's cool and all that.  One of the many 
reasons to like Struts :-).

But, more than a few people have complained that the populate() method throws an 
exception the first time that it runs into a problem doing a conversion.  Because the 
list of request parameters is stored in something like a Hashtable or HashMap in your 
servlet container, that means you have no idea which (if any) conversions were 
performed successfully -- you have to throw them away.  What some people would prefer 
is the opportunity to do all the conversions that can be done, and report all the 
failures in one custom exception at the end of the process.

"That doesn't seem to hard," you might say.  "All I need to do is create a MyBeanUtils 
class with a custom copyProperties() method that behaves the way *I* want it to, and 
use it instead of the standard one".  In other words, your application will call 
MyBeanUtils.populate() instead of BeanUtils.populate().

But ... how do you convince *Struts* to use your version of
copyProperties() instead of the standard one ... since it requires modification of all 
calling programs to use MyBeanUtils.populate() instead of BeanUtils.populate()?  This 
is why the language purists in this thread have been jumping up and down saying that 
you cannot override a static method in a manner that is transparent the calling class. 
Requiring the caller to switch the class name is generally not an option.

However, if BeanUtils were to provide a way to ask for an instance of some class that 
implemented the "bean utils" interface, and also provided a factory mechanism so that 
you could plug in your own implementations, you'd be a happy camper.  You could 
provide your own custom implementation, and because Struts would ask the appropriate 
factory method for an instance of BeanUtils, it would also use your custom 
implementation.

For the specific case of BeanUtils, we are halfway there (using the singleton pattern) 
already on the HEAD branch of the CVS repository.  It turns out that we need to do 
this so that commons-beanutils can be placed in a shared class loader in a servlet 
container (i.e. in the common/lib directory for Tomcat) but allow each web application 
to have its own bean named "foo" with no interference.  What remains to be done is a 
mechanism to register your replacement BeanUtilsBean (I'm going to suggest using 
commons-discovery for this), but you can count on support for this some time in the 
1.2.x lifecycle.

In the mean time, I suggest you avoid this trap for your application specific classes, 
and implement the singleton pattern instead.

Craig

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

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

Reply via email to