Please consider the following (pseudo) C# example:
public class AS400Server
{
static AS400 server;
static AS400Server()
{
server = new AS400Connection("SERVERNAME");
}
static ~AS400Server() // This is not real C#
{
server.disconnect();
}
static int GetServer()
{
return server;
}
}
I know this probably can be emulated using a singleton,
The singleton design pattern certainly can do that, and is easily used in Ruby by including module "Singleton" (except for the destruction part - although I expect a finaliser could do that for you, but I've not used them myself).
When you started to talk about these, I thought you were after 'structors for a class, rather than an instance. These are, of course, very easy in Ruby, as a class is just an object like any other. In fact, you can have little factories that will pump out classes, if you want.
I still believe
having static destructors will be nice because:
1. I like the constructor/destructor symmetry in C++
Actually, I like the c++ destructors too. I'd say they are one of the very few things that I miss about it I quite often made use of a "stack object". It's an object with no interface except for it's 'structors. You would declare them "on the stack" in c++ (ie, without using new), so they are local to a code block. They're really useful for doing setup within a code block and ensuring that teardown happens when you exit it. They seem like a DRY way to specify the use of a mode within a code block:
class StackObject
{
public:
StackObject() {do_setup_code();}
~StackObject() {do_teardown_code();}
private:
void do_setup_code();
void do_teardown_code();
};
And to use...
{
// Setup resource.
StackObject stack_object;
// Do stuff with the mode being setup by the stack object.
// Tear down happens automatically at block exit.
}
However, a very similar idea is possible in Ruby, and can be achieved with passing code blocks...
def run_within_mode
setup_code
yield
ensure
teardown_code
end
And to use:
# Here, the mode is not in use yet.
run_within_mode do
# Anything here is happening with the mode! Hooray!
end
# And the mode's gone again.
As well as ensuring the resource is cleaned up, both of these approaches are exception safe too.
Cheers,
Ben
···
On 31 Mar 2006, at 20:58, PrimaryKey wrote: