Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

C++ Abstract Factory

I have the following code which compiles and works :-

#include <iostream>
#include <string>
#include <new>

using namespace std;

class Message
{
public:
virtual ~Message() {}
virtual Message* clone() const = 0;
virtual string get_type() const = 0;
virtual void set(const string s1, const string s2) = 0;
virtual void print() const = 0;
};

class Fax: public Message
{

private:
string m_number;
string m_image;

public:
Fax() {}
Fax(const string num, const string image) : m_image(num), m_number(num) {}
virtual Message* clone() const { return new Fax(*this);}
virtual string get_type() const { return "Fax"; }
virtual void set(const string num, const string image) { m_number = num; m_image = image; }
virtual void print() const { cout << " * Fax: number = " << m_number << " image = " << m_image << "\n"; }
};

class AbstractFactory
{
public:
virtual Message* createMessage() const = 0;
};

class FaxFactory : public AbstractFactory
{
virtual Message* createMessage() const { return new Fax; }
};

int main()
{
FaxFactory f;

return 0;
}

From FaxFactory, I'm returning "new Fax" which is fine, but where do I set the values for "Fax" How do I access the methods in "class Fax: public Message" without creating an object of Fax ? The whole idea of AbstractFactory pattern is that it creates interface to create objects from Message interface. If I need to do: Fax f1 and then f1.set("34325", "..."), then why would I need to bother with this pattern ?
[1760 byte] By [ami] at [2007-11-11 9:57:21]
# 1 Re: C++ Abstract Factory
You're right, you can't call a fax member function without having a fax object. However, the Asbtract pattern is implemented differently: it uses a static member function to create the object, and it returns a (preferably) a smart pointer to that object. When you have a static member function, you don't need to have an object to call it. You can call it for the class:
Fax* pfax= Fax::Create();
Danny at 2007-11-11 20:59:46 >