Whether the following program implement the factory Design

S

sunny

Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.
 
M

Michael DOUBEZ

sunny a écrit :
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.

#include said:
using namespace std;

class Quad
{
public:
void Area();
void Desc();
};

class Square : public Quad
{
public:
Square() {};

void Area(int x)
{
cout<<"Area of square is = "<<x*x<<endl;
}

void Desc()
{
cout<<"This Derived class Square from Base Class Quad"<<endl;
}
};

class Rectangle : public Quad
{
public:
Rectangle() {};

void Area(int x, int y)
{
cout<<"Area of Rectangle is = "<<x*y<<endl;
}

void Desc()
{
cout<<"This Derived class Rectangle from Base Class Quad"<<endl;
}

};

class Creator
{
public:
Quad* Creator::Create(int id)
{
if (id==2)
return new Square;
else
return new Rectangle;
}
};

int main(int argc, char* argv[])
{
Creator mcreator;
if (argc<=2)
{
Square *square = reinterpret_cast<Square*>(mcreator.Create(2));
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cast<Rectangle*>(mcreator.Create(1));
rectangle->Area(3,4);
rectangle->Desc();
}

return 0;
}



Are you thinking of
- "Abstract" Factory design
http://en.wikipedia.org/wiki/Abstract_factory_pattern
or
- Factory "method" design
http://en.wikipedia.org/wiki/Factory_method_pattern
Which seems more likely from your code
1. Make Quad::Area and Quad::Desc virutal
2. If you want to prevent creation of Square and Retangle
outside the factory, make their constructor protected and declare
Creator as a friend class
3. Consider using enum as parameter of Creator::Create and
perhaps make it static

Michael
 
V

vijay

Michael said:
sunny a écrit :
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.

#include said:
using namespace std;

class Quad
{
public:
void Area();
void Desc();
};

class Square : public Quad
{
public:
Square() {};

void Area(int x)
{
cout<<"Area of square is = "<<x*x<<endl;
}

void Desc()
{
cout<<"This Derived class Square from Base Class Quad"<<endl;
}
};

class Rectangle : public Quad
{
public:
Rectangle() {};

void Area(int x, int y)
{
cout<<"Area of Rectangle is = "<<x*y<<endl;
}

void Desc()
{
cout<<"This Derived class Rectangle from Base Class Quad"<<endl;
}

};

class Creator
{
public:
Quad* Creator::Create(int id)
{
if (id==2)
return new Square;
else
return new Rectangle;
}
};

int main(int argc, char* argv[])
{
Creator mcreator;
if (argc<=2)
{
Square *square = reinterpret_cast<Square*>(mcreator.Create(2));
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cast<Rectangle*>(mcreator.Create(1));
rectangle->Area(3,4);
rectangle->Desc();
}

return 0;
}



Are you thinking of
- "Abstract" Factory design
http://en.wikipedia.org/wiki/Abstract_factory_pattern
or
- Factory "method" design
http://en.wikipedia.org/wiki/Factory_method_pattern
Which seems more likely from your code
1. Make Quad::Area and Quad::Desc virutal
once you make this virtual you can remvoe reintrepret cast . then this
desing will be factory pattern and your factory method is Creator .
 
N

Noah Roberts

sunny said:
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.

#include said:
using namespace std;

class Quad
{
public:
void Area();
void Desc();
};

class Square : public Quad
{
public:
Square() {};

void Area(int x)
{
cout<<"Area of square is = "<<x*x<<endl;
}

void Desc()
{
cout<<"This Derived class Square from Base Class Quad"<<endl;
}
};

class Rectangle : public Quad
{
public:
Rectangle() {};

void Area(int x, int y)
{
cout<<"Area of Rectangle is = "<<x*y<<endl;
}

void Desc()
{
cout<<"This Derived class Rectangle from Base Class Quad"<<endl;
}

};

class Creator
{
public:
Quad* Creator::Create(int id)
{
if (id==2)
return new Square;
else
return new Rectangle;
}
};

int main(int argc, char* argv[])
{
Creator mcreator;
if (argc<=2)
{
Square *square = reinterpret_cast<Square*>(mcreator.Create(2));

Don't use reinterpret_cast in cases like this. Use dynamic_cast or
static_cast if you are conserned about speed. Possibly better use
boost::polymorphic_downcast.

I don't know for certain if your use of reinterpret_cast in this
particular case creates undefined behavior but minor changes to the
objects in questions (introducing MI for instance) definately will.
The whole point of a factory is to hide this kind of detail.

Objects created by a factory shouldn't need to be cast like this. If
you are casting down from creation of the object then the factory is
pointless. Yes, creator is a factory but the objects it is creating
are not polymorphic so it makes no sense. That is the reasoning behind
the other answers you got.
 
S

Salt_Peter

sunny said:
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.

#include said:
using namespace std;

class Quad
{
public:
void Area();
void Desc();
};

class Square : public Quad
{
public:
Square() {};

void Area(int x)
{
cout<<"Area of square is = "<<x*x<<endl;
}

void Desc()
{
cout<<"This Derived class Square from Base Class Quad"<<endl;
}
};

class Rectangle : public Quad
{
public:
Rectangle() {};

void Area(int x, int y)
{
cout<<"Area of Rectangle is = "<<x*y<<endl;
}

void Desc()
{
cout<<"This Derived class Rectangle from Base Class Quad"<<endl;
}

};

class Creator
{
public:
Quad* Creator::Create(int id)
{
if (id==2)
return new Square;
else
return new Rectangle;
}
};

int main(int argc, char* argv[])
{
Creator mcreator;
if (argc<=2)
{
Square *square = reinterpret_cast<Square*>(mcreator.Create(2));
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cast<Rectangle*>(mcreator.Create(1));
rectangle->Area(3,4);
rectangle->Desc();
}

return 0;
}

Factory design patterns can be a pain to work with, specially when
their allocations are leaked / ignored. I have no respect for any code
that uses reinterpret_cast flagrantly (and in many cases - the same
goes for dynamic_cast).

Here is one based on boost::shared_ptr with Shape having protected
ctors, disabled copy-ctors and a factory friend. Note: STL container is
*not* copying Shapes here.
A Square is_a Rectangle
Factory has a create() that produces the shape required via specified
template parameter.

#include <iostream>
#include <ostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct Shape
{
Shape() { }
Shape(const Shape& copy); // disabled
virtual ~Shape() = 0;
virtual double area() const = 0;
virtual void description() const = 0;
};

Shape::~Shape() { std::cout << "~Shape()\n"; }

class Rectangle : public Shape
{
double width, height;
friend class ShapeFactory;
protected:
Rectangle(double w, double h)
: width(w), height(h)
{
std::cout << "Rectangle()\n";
}
public:
~Rectangle()
{
std::cout << "~Rectangle()\n";
}
double area() const { return width * height; }
void description() const
{
std::cout << "Rectangle with area = ";
std::cout << area() << std::endl;
}
};

class Square : public Rectangle
{
friend class ShapeFactory;
protected:
Square(double w, double dummy)
: Rectangle(w, w)
{
std::cout << "Square()\n";
}
public:
~Square()
{
std::cout << "~Square()\n";
}
double area() const { return Rectangle::area(); }
void description() const
{
std::cout << "Square with area = ";
std::cout << area() << std::endl;
}
};

class Triangle : public Shape
{
double width, height;
friend class ShapeFactory;
protected:
Triangle(double w, double h)
: width(w), height(h)
{
std::cout << "Triangle()\n";
}
public:
~Triangle()
{
std::cout << "~Triangle()\n";
}
double area() const { return 0.5 * width * height; }
void description() const
{
std::cout << "Triangle with area = ";
std::cout << area() << std::endl;
}
};

class ShapeFactory
{
public:
template< typename ShapeType >
boost::shared_ptr< ShapeType >
create(const double w = 0.0, const double h = 0.0) const
{
return boost::shared_ptr< ShapeType >(new ShapeType(w, h));
}
};

int main()
{
ShapeFactory factory;

typedef boost::shared_ptr< Shape > SP_Shapes;
std::vector< SP_Shapes > vshapes;
vshapes.push_back( factory.create< Triangle >(10.1, 10.2) );
vshapes.push_back( factory.create< Rectangle >(4.2, 25.1) );
vshapes.push_back( factory.create< Square >(9.3) );

typedef std::vector< SP_Shapes >::iterator VIter;
for( VIter viter = vshapes.begin();
viter != vshapes.end();
++viter )
{
(*viter)->description();
}

// std::vector< SP_Shapes > vshapes2(vshapes); // ok
}

/*
Triangle()
Rectangle()
Rectangle() // <- Square
Square()
Triangle with area = 51.51
Rectangle with area = 105.42
Square with area = 86.49
~Triangle()
~Shape()
~Rectangle()
~Shape()
~Square()
~Rectangle()
~Shape()
*/
 
S

Salt_Peter

Michael said:
Salt_Peter a écrit :
A Square is_a Rectangle

From the C++ point of view, saying that "A Square is_a Rectangle" leads
do design problems.

You might even think that a Circle is_an Ellipse ? :)
See http://www.parashift.com/c++-faq-lite/proper-inheritance.html
Chapter [21.6] and further chapters on Ellipse/Circle Dilemna.

We've been through that x times.
A square is a special type of rectangle. Period. Whether that satisfies
the hierarchy depends on the requirements. In this case - its perfectly
valid.
A circle can never be an ellipse because of the mathematical
description involved to explain the two distinct Shapes. An Ellipse
might be described starting from 2 circles (has_a relationship). etc.

The 2 relationships are completely unrelated in any way.
 
N

Noah Roberts

Salt_Peter said:
Michael said:
Salt_Peter a écrit :
sunny wrote:
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.
A Square is_a Rectangle

From the C++ point of view, saying that "A Square is_a Rectangle" leads
do design problems.

You might even think that a Circle is_an Ellipse ? :)
See http://www.parashift.com/c++-faq-lite/proper-inheritance.html
Chapter [21.6] and further chapters on Ellipse/Circle Dilemna.

We've been through that x times.
A square is a special type of rectangle. Period. Whether that satisfies
the hierarchy depends on the requirements. In this case - its perfectly
valid.

Actually, what you have done is shown that is_a means two different
things when talking about real life and when talking about code. Yes,
mathematically a square is defined as a rectangle with all sides equal.
However, a square as a subclass of rectangle is inappropriate for the
simple reason that a square cannot respond to a rectangle's interface
and retain the properties inherent to a square.

Now, you can retain the mathematical purity by having one class,
rectangle, for which a rectangle that happens to have all sides equal
can occur and such rectangles would be squares. What you can't have,
without running afoul of major problems caused by poor design, is an
object that "is a rectangle" but enforces the constraints of a square.

To illustrate:

Rectangle * r = new Square(5);
....
r->SetWidth(3);
r->SetHeight(10);
assert(r->Width() == 3 && r->Height() == 10);


Having a square be a rectangle violates the LSP in that it doesn't
adhere to the post conditions of rectangle operations. It may be ok to
do in initial designs where you say, "But I'll never use a square
interchangeably with a rectangle in that manner," but eventually you
almost always do.
 
S

Salt_Peter

Noah said:
Salt_Peter said:
Michael said:
Salt_Peter a écrit :
sunny wrote:
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.
A Square is_a Rectangle

From the C++ point of view, saying that "A Square is_a Rectangle" leads
do design problems.

You might even think that a Circle is_an Ellipse ? :)
See http://www.parashift.com/c++-faq-lite/proper-inheritance.html
Chapter [21.6] and further chapters on Ellipse/Circle Dilemna.

We've been through that x times.
A square is a special type of rectangle. Period. Whether that satisfies
the hierarchy depends on the requirements. In this case - its perfectly
valid.

Actually, what you have done is shown that is_a means two different
things when talking about real life and when talking about code. Yes,
mathematically a square is defined as a rectangle with all sides equal.
However, a square as a subclass of rectangle is inappropriate for the
simple reason that a square cannot respond to a rectangle's interface
and retain the properties inherent to a square.

Now, you can retain the mathematical purity by having one class,
rectangle, for which a rectangle that happens to have all sides equal
can occur and such rectangles would be squares. What you can't have,
without running afoul of major problems caused by poor design, is an
object that "is a rectangle" but enforces the constraints of a square.

To illustrate:

Rectangle * r = new Square(5);
...
r->SetWidth(3);
r->SetHeight(10);
assert(r->Width() == 3 && r->Height() == 10);

Says who? Where is it written that i can't overide those 2 setters?
Whats preventing me from specializing the needs of this particular type
of rectangle without having to reconstruct the class from scratch?
So, just for the sake of discussion - let me add a requirement - since
none have been put forth and since that is what this is presumably all
about:

I need to include Squares to store anything that remotely looks or
behaves like a Rectangle, excluding other shapes?
std::vector< Rectangle > vrect;

So: how do i do that?
Having a square be a rectangle violates the LSP in that it doesn't
adhere to the post conditions of rectangle operations. It may be ok to
do in initial designs where you say, "But I'll never use a square
interchangeably with a rectangle in that manner," but eventually you
almost always do.

Yes, the interface violates design by object in its pure sense. That
however, that was not given as a requirement here.
 
N

Noah Roberts

Salt_Peter said:
Noah Roberts wrote:

Says who?

Says Rectangle. If I call SetWidth on a rectangle then the width I get
from that rectangle must certainly be the width I set and not some
other value....same as with height. These are perfectly logical
assumptions to make. If I can't make these assumptions then the
Rectangle interface is useless.
Where is it written that i can't overide those 2 setters?

You can. And you can do so in a way that breaks the rectangle
interface. As such, your subclass is no longer an "is_a" but an
"almost_a". Public inheritence should /always/ be "is a".
Whats preventing me from specializing the needs of this particular type
of rectangle without having to reconstruct the class from scratch?

"Is a" is another way of wording the LSP, which states that a function
that operates on type T must be able to work with any subclass of type
T interchangeably through the T interface (it's actually worded very
differently but that is the essense). A square being a subclass of
rectangle breaks this because a square does not meet the post
conditions of the interface of a rectangle and functions that operate
on a rectangle and expect rectangle behavior might be broken when
called with a square as a parameter.
So, just for the sake of discussion - let me add a requirement - since
none have been put forth and since that is what this is presumably all
about:

I need to include Squares to store anything that remotely looks or
behaves like a Rectangle, excluding other shapes?
std::vector< Rectangle > vrect;

You can't. First of all because all the elements of your vector are
Rectangles. However, even if you created your vector with pointers
instead (allowing the inclusion of base class instances in their
entirety) you still have the problem that functions that work with that
vector can't depend on the objects in it obeying the interface of
rectangle. This is why it simply doesn't work. For your highly
constrained example you would need to add a level of indirection by
creating a wrapper class that would only expose an interface that makes
sense for both rectangle and square but could contain either.
Depending on the situation the pre/post conditions of operations would
be loosened or tightened in order that both objects could be
interchanged and meet the requirements of clients.
So: how do i do that?

Through a third interface and composition.
Yes, the interface violates design by object in its pure sense. That
however, that was not given as a requirement here.

Since when is attempting to use sound principles and practices NOT
given as a requirement?? IMHO it always is unless otherwise stated.
If you desire to write rigid and fragile code then yes, there is no
need to worry about such mundain details.

The square/rectangle inheritance problem is a simple example of a much
larger and commonly seen design problem. It may seem meaningless or
petty to harp on square and rectangle but the inheritance problems it
illustrates are seen quite often in code and the fragility they
introduce can make life very difficult and the product nearly
impossible to maintain.
 
M

Michael DOUBEZ

Salt_Peter a écrit :
Noah said:
Salt_Peter said:
Michael DOUBEZ wrote:
Salt_Peter a écrit :
sunny wrote:
Does this following program implement the factory design.if not what
are things that i have to change in order to make this following
program to be designed to factory design pattern.
A Square is_a Rectangle
From the C++ point of view, saying that "A Square is_a Rectangle" leads
do design problems.

You might even think that a Circle is_an Ellipse ? :)
See http://www.parashift.com/c++-faq-lite/proper-inheritance.html
Chapter [21.6] and further chapters on Ellipse/Circle Dilemna.
We've been through that x times.
A square is a special type of rectangle. Period. Whether that satisfies
the hierarchy depends on the requirements. In this case - its perfectly
valid.

Nobody try to tell you how to code your program: if you want to
specialize the class Rectangle into Square, that's fine for me. But it
can lead to design problem nonetheless and not take this inheritance as
a rule without further understanding.

In this particular example, it doesn't violate object design but the
inheritance also doesn't serve any purpose. Unless there was a point I
didn't see to make SQuare inherit from Rectangle ?

Says who? Where is it written that i can't overide those 2 setters?
Whats preventing me from specializing the needs of this particular type
of rectangle without having to reconstruct the class from scratch?

You can do anything you want with your code within what C++ allow but it
is a personnal decision and other readers should be aware of the pros
and cons.
So, just for the sake of discussion - let me add a requirement - since
none have been put forth and since that is what this is presumably all
about:

I need to include Squares to store anything that remotely looks or
behaves like a Rectangle, excluding other shapes?
std::vector< Rectangle > vrect;

So: how do i do that?

You put what you need to do generically in a virtual class
(BehaveLikeRectangle) inherited by Square and Rectangle.
Yes, the interface violates design by object in its pure sense. That
however, that was not given as a requirement here.

The inheritance between Square and Rectangle was neither required in the
original post.
 

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
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top