constructor or factory or builder

D

David Bellot

Hi,

if I consider the Factory Method design pattern, then I should have the
following objects:

Object and ObjectFactory which are usually abstract classes

Then for each subclasses like ConcreteObject1, ConcreteObject2, .... I
must have a ConcreteObjectFactory1, ConcreteObjectFactory1, ...

What is the benefit using a Factory instead of a constructor to
instantiate a ConcreteObject ?

David
 
M

mlimber

David said:
Hi,

if I consider the Factory Method design pattern, then I should have the
following objects:

This is not really the factory method design pattern as defined by the
GoF. It's just using factory objects.
Object and ObjectFactory which are usually abstract classes

Then for each subclasses like ConcreteObject1, ConcreteObject2, .... I
must have a ConcreteObjectFactory1, ConcreteObjectFactory1, ...

What is the benefit using a Factory instead of a constructor to
instantiate a ConcreteObject ?

This is not really a C++ language question. You probably want to ask in
comp.object.

But to give you a common example in C++, you can use different
look-and-feels for GUI elements through a factory:

struct AbstractButton
{
virtual ~AbstractButton() {}
//...
};

struct AbstractFactory
{
virtual ~AbstractFactory() {}
virtual std::auto_ptr<AbstractButton> CreateButton() const = 0;
// ...
};

struct SquareButton : AbstractButton { /*...*/ };
struct RoundedButton : AbstractButton { /*...*/ };

struct SquareFactory : AbstractFactory
{
std::auto_ptr<AbstractButton> CreateButton() const
{
return auto_ptr<AbstractButton>( new SquareButton );
}
// ...
};

struct RoundedFactory : AbstractFactory
{
std::auto_ptr<AbstractButton> CreateButton() const
{
return auto_ptr<AbstractButton>( new RoundedButton );
}
// ...
};

struct Dialog
{
Dialog( const AbstractFactory& factory )
{
// ... create and use buttons abstractly, e.g.,
std::auto_ptr<AbstractButton> button = factory.CreateButton();
// ... now use AbstractButton's interface here
// and it will apply to either square or rounded buttons
// depending on which factory was passed to this constructor
}
// ...
};

For a more sophisticated implementation of this sort of thing, see
chapters 8 and 9 of _Modern C++ Design_.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top