Self-Registering classes in C#
I have to make a program that implements a Shape Factory (that is a container that keep all kind of geometric shapes). The trick is, it has to be developped in such a way, to allow adding of new shapes (classes derived from a base abstract class "Shape") without modifing any of the main program's code...
I've done it in C++... and it is something like that:
//in main program:
class Shape
{
virtual void Draw() = 0; //abstract
}
//in new file (added afterwards... )
class Circle : Shape
{
void Draw() {...}
}
namespace
{
//by initializing this const, i actually call the function RegisterCircle(...), that
// registeres this class (addes some information in a vector)
const bool registered = RegisterCircle(...);
}
because of namespaces in C++, this is OK...
But in C#, I can not have variables inside a namespace (not included in a class). So I could use that variable, as a STATIC one, inside my "Circle" class. This would be ok, but for one thing:
in C#, no variable (even a static one) gets initialized until its owner class is instantiated or a static member is called (used) in a program... And I can not instantiate or call a static member from the main program, because I'm not allowed to modify main program.
So, please help!!!
bilnaadPosted Oct 10, 2004, 8:43 AM
viperashuPosted Oct 10, 2004, 8:23 AM
jsheplerPosted Oct 8, 2004, 10:01 AM
public class Shape { ... public virtual void Draw() { // code here that executes when the object actually is a Shape, the derived class // doesn't override this method, or the derived class explicitly calls this method // via base.Draw(); } } public class Circle : Shape { ... public override void Draw() { // code here that executes instead of the base method // if you need to call the base method as well, use base.Draw(); } }As for variables, if you mark the base class' variables as protected, the dervied class can access them - static or otherwise. Your main program works with the Shape "aspect" of the Circle object. When you call the base's Draw() method, the Circle's Draw() method will be executed instead.