Factory design
John C
johnch_atms at hotmail.com
Sun May 28 16:56:15 PDT 2006
So I've got an abstract class with a factory method. Users call the
factory method to instantiate an instance. It calls a function which
modules that contain the contrete class must implement.
But I'm getting linking errors. OptLink thinks 'createXmlReaderImpl' is
undefined, presumably because it's expecting the body to be contained in
the same module.
Note that if 'createXmlReaderImpl' is declared with 'extern(C)', then it
links without errors.
I've seen a similar technique used before. The main entry point in
dmain.d in phobos, for example. Ideas?
module model;
// Modules containing the concrete class implement this.
XmlReader createXmlReaderImpl(Stream input);
abstract class XmlReader {
static XmlReader create(Stream input) {
return createXmlReaderImpl(input);
}
// Abstract methods...
}
// impl1 implementation wraps some C library.
module impl1;
import model;
XmlReader createXmlReaderImpl(Stream input) {
return new XmlReaderImpl(input);
}
class XmlReaderImpl : XmlReader {
// Implements XmlReader's abstract methods
private this(Stream input) ...
}
// impl2 implementation wraps some other C library.
module impl2;
import model;
XmlReader createXmlReaderImpl(Stream input) {
return new XmlReaderImpl(input);
}
class XmlReaderImpl : XmlReader {
// Implements XmlReader's abstract methods
private this(Stream input) ...
}
// User code that chooses which implementation to use.
module program;
import model, impl1; // Choosing impl1
void main() {
Stream s = ...;
XmlReader reader = XmlReader.create(s);
}
Thanks,
John.
More information about the Digitalmars-d-learn
mailing list