My Log Class question

P

Peter

Hi
I have a JLog class which is doing "logging", it will write some
string into a specific file.
Every class can init it and use it.
My question is: every class init one JLog object and use it OR only
one class init one JLog and pass it to the classes which need it?

I think the second is better, because it use lesser memory.
thanks
from Peter ([email protected])
 
A

Anthony Borla

Peter said:
Hi
I have a JLog class which is doing "logging", it will
write some string into a specific file.

Every class can init it and use it.

My question is: every class init one JLog object and
use it OR only one class init one JLog and pass it to the
classes which need it?

You [probably] only need one logger object per application [assuming there
is one log file to which all logger object user's (i.e. objects doing
logging) will be writing]. So, just implement it as a Singleton, thus
ensuring that:

- There is a single instance per application

- All users wishing to use it can easily do so; there is
no need to pass references to this object

Simple example [there are variations on this design]:

class Logger
{
...
private Logger(...) { ... }
private static Logger;

public static Logger getInstance()
{
return logger != null ? logger : (logger = new Logger(...));
}
...
}

// in method X of object Y:
...
Logger.getInstance().write(new LogEntry(...));
...

// in method X of object Z:
...
Logger.getInstance().write(new LogEntry(...));
...

The Singleton pattern provides the convenience of global variables without
the associated dangers, and can be an extremely useful design. Google on
"Singleton Pattern" for more details.

I hope this helps.

Anthony Borla
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,282
Latest member
RoseannaBa

Latest Threads

Top