Factory design
Carlos Santander
csantander619 at gmail.com
Sun May 28 18:55:18 PDT 2006
John C escribió:
> 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);
>
How about putting it in an abstract class, say a singleton?
> 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.
--
Carlos Santander Bernal
More information about the Digitalmars-d-learn
mailing list