dcsimg
Correct use of Singleton?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Nigel_Smith
Posted On:   Sunday, March 2, 2003 03:39 PM

In my multi user web aplication I need to introduce some activity reporting.

To achieve this I need to write to a file all activity (e.g. one record for login,

another for a successful enquiry, another for a successful transfer etc.).

I am thinking of implementing a Singleton class to control access to this file.

Is this the correct pattern to use? Should the method that writes to the file be syncronised?

Nigel

Re: Correct use of Singleton?

Posted By:   Sriram_Gopalan  
Posted On:   Monday, May 12, 2003 04:52 PM

There are two questions to ask before deciding to use a singleton:

  1. Is it absolutely necessary to control the number of instances of this class? Is there any problem with having multiple instances of this class? Will there be resource contention or deadlocks if I don't control the number of instances?
  2. Do I need to make this class globally accessible?

In your case the second is probably true. Whether the first question is true or not is for you to decide. If that is not scrictly true, you could just instantiate and keep a globally accessible object.

The advantage is, if this object gets used in many places, the calling code will look like

ActivityRecorder.record(...)
rather than
ActivityRecorder.getInstance().record(...)

Singleton is a simple pattern to use and hence is also easy to misuse. In my opinion, the answer to the first question is the key. If having multiple instances of the class will not cause any harm, just use a regular class with static methods.

Re: Correct use of Singleton?

Posted By:   Anonymous  
Posted On:   Tuesday, March 4, 2003 11:00 PM

You can use Log4j framework instead.
http://jakarta.apache.org/log4j/docs/
About | Sitemap | Contact