[EMAIL PROTECTED] wrote:
>
> I have a gizmo that keeps track of resources for a program. The problem
> is that Im ending up passing this gizmo to every child component and
> that is beginning to bug me. In C++ I ould just create a global static
> var and let everyone access it. This is one of those rare cases where
> its a good idea. ALL parts use the same instance and the instance is
> read once (at the beginning) and written once(at program shutdown)
> anyone have any more elgant solution then passing it all over the damn
> place ?
>
> --rob
>
> ----------------------------------------------------------------------
> To UNSUBSCRIBE, email to [EMAIL PROTECTED]
> with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]
The singleton pattern is basically :
o a class with a private constructor
o a class that can only be instantiated with a public method call
(in which you control access to the SINGLETON resource).
thus you can write the following :
public class NetworkPrinter {
protected PaperStack paper
private static NetworkPrinter thePrinter = new NetworkPrinter();
private NetworkPrinter ( )
{
}
public static NetworkPrinter getInstance()
{
// When we get `thePrinter' has already been constructed
return (thePrinter);
}
...
public boolean printDocument( Document doc )
{
...
}
...
}
Use it the form
void someBanalFunction() {
NetworkPrinter globalPrinter = NetworkPrinter.getInstance();
globalPrinter.printDocument( new Document( new File( "life.txt") );
}
Or perhaps alternatively the lazy singleton.
public class NetworkPrinter {
protected PaperStack paper
protected static Object locker = new Object();
private static NetworkPrinter thePrinter = null;
private NetworkPrinter ( )
{
}
public static NetworkPrinter getInstance()
{
if ( thePrinter != null ) {
// Thread Safety - Double Guard technique
synchronized( locker )
if ( thePrinter != null ) {
thePrinter = new NetworkPrinter();
}
}
return (thePrinter);
}
...
public boolean printDocument( Document doc )
{
...
}
...
}
--
Adios
Peter
-----------------------------------------------------------------
import std.Disclaimer; // More Java for your Lava, Mate.
"Give the man, what he wants. £££" [on Roy Keane, Quality Player]
----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]