/* * factory.cpp * * Example of Factory Method * * Define an interface for creating an object, but * let subclasses decide which class to instantiate. */ #include #include class Document { public: virtual void operation() = 0; }; class DrawingDocument : public Document { public: void operation() { std::cout << "DrawingDocument\n"; } }; class Application { public: virtual Document* factoryMethod() = 0; void operation() { } }; class DrawingApplication : public Application { public: virtual DrawingDocument* factoryMethod() { return new DrawingDocument; } }; class Client { public: Client(Application& creator) : _creator(creator) {} void dosomething() { Document* pproduct = _creator.factoryMethod(); pproduct->operation(); } private: Application& _creator; }; int main() { DrawingApplication drawingApplication; Client client(drawingApplication); client.dosomething(); }