473,782 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Whether the following program implement the factory Design

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<iostre am>
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<<end l;
}

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<<end l;
}

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_cas t<Square*>(mcre ator.Create(2)) ;
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cas t<Rectangle*>(m creator.Create( 1));
rectangle->Area(3,4);
rectangle->Desc();
}

return 0;
}
Dec 7 '06 #1
10 2350
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<iostre am>
>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<<end l;
}

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<<end l;
}

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_cas t<Square*>(mcre ator.Create(2)) ;
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_ca st<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
Dec 7 '06 #2

Michael DOUBEZ wrote:
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<iostre am>
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<<end l;
}

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<<end l;
}

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_cas t<Square*>(mcre ator.Create(2)) ;
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cas t<Rectangle*>(m creator.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 .
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
Dec 7 '06 #3

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.

#include<iostre am>
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<<end l;
}

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<<end l;
}

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_cas t<Square*>(mcre ator.Create(2)) ;
Don't use reinterpret_cas t in cases like this. Use dynamic_cast or
static_cast if you are conserned about speed. Possibly better use
boost::polymorp hic_downcast.

I don't know for certain if your use of reinterpret_cas t 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.
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cas t<Rectangle*>(m creator.Create( 1));
rectangle->Area(3,4);
rectangle->Desc();
}
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.

Dec 7 '06 #4
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.

#include<iostre am>
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<<end l;
}

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<<end l;
}

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_cas t<Square*>(mcre ator.Create(2)) ;
square->Area(3);
square->Desc();
}
else
{
Rectangle *rectangle =
reinterpret_cas t<Rectangle*>(m creator.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_cas t flagrantly (and in many cases - the same
goes for dynamic_cast).

Here is one based on boost::shared_p tr 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(doubl e 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_p tr< ShapeType >
create(const double w = 0.0, const double h = 0.0) const
{
return boost::shared_p tr< ShapeType >(new ShapeType(w, h));
}
};

int main()
{
ShapeFactory factory;

typedef boost::shared_p tr< Shape SP_Shapes;
std::vector< SP_Shapes vshapes;
vshapes.push_ba ck( factory.create< Triangle >(10.1, 10.2) );
vshapes.push_ba ck( factory.create< Rectangle >(4.2, 25.1) );
vshapes.push_ba ck( 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(vshape s); // 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()
*/

Dec 7 '06 #5
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-lit...heritance.html
Chapter [21.6] and further chapters on Ellipse/Circle Dilemna.
Dec 7 '06 #6

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-lit...heritance.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.

Dec 8 '06 #7

Salt_Peter wrote:
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-lit...heritance.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.

Dec 8 '06 #8

Noah Roberts wrote:
Salt_Peter wrote:
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-lit...heritance.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.

Dec 8 '06 #9

Salt_Peter wrote:
Noah Roberts wrote:
To illustrate:

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

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.
>


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.
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.

Dec 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3221
by: lawrence | last post by:
To call I would do something like: $headline = McSelectJustOneField::callDatastore("cbHeadline"); Is this the correct use of the static keyword, to implement a Singleton design?
14
23145
by: Medi Montaseri | last post by:
Hi, I think my problem is indeed "how to implement something like java's final in C++" The long version.... I have an abstract base class which is inherited by several concrete classes. I have a group of methods that I'd like to implement in the base class
4
2527
by: max | last post by:
Hello, I analyze this design pattern for a long time but I do not understand how this pattern work and what the purpose is? (I looked a this site http://www.dofactory.com/Patterns/PatternAbstract.aspx). Could anybody try to explain me in his own words how this pattern work and what the purpose is? thanks in advance
11
4309
by: FluffyCat | last post by:
In Febraury - April of 2002 I put together in Java examples of all 23 of the classic "Gang Of Four" design patterns for my website. Partly I wanted to get a better understanding of those patterns. They are still online at http://www.fluffycat.com/java/patterns.html Since September 2003 I've mainly been using PHP, and now that PHP 5 is becoming more available I am going to try the same thing I did in Java with PHP.
8
4814
by: deko | last post by:
Which layer should a Factory class go in? DA - Data Access BL - Business Logic UI - User Interface ??
0
1546
by: ma740988 | last post by:
I'm going through modern C++ design looking for tips and while hi-tech I suspect one solution to my issue would involve the factory design pattern. // algorithms.h class Algorithms { protected: typedef std::deque<double> DDEQUE; // need to make this even more generic to support floats .. i.e float and double public:
1
2344
by: orel | last post by:
Please, As i tried hundreds different implementation to make it work and actually didn't succeed, can someone here help me to understand and use the implementation of the Object Factory design pattern. I'm using gcc 3.4.2 on Mingw. The factory is the same as the one in Modern C++ design (without error checking) , like this :
0
260
by: sunny | last post by:
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<iostream>
4
5019
by: Pallav singh | last post by:
Hi , when should i select Factory Method / Prototype Design Pattern during my design phase ?? as both look similar to me Thanks in Advance Thanks Pallav
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.