Re: Factory Design Pattern
<mail.dpant@gmail.com> schreef in bericht
news:918c7ac8-f418-4152-8da3-f9a4e80dd6a8@a8g2000prf.googlegroups.com...
I have written a Factory design Patten in C++. can anybody comment is
it the correct way to do it?
#include "stdafx.h"
#include <iostream>
using namespace std;
/* Display Driver hierarchy */
class DisplayDriver{
public:
DisplayDriver(){}
virtual void display()=0;
};
class LowResolutionDD:public DisplayDriver{
public:
void display(){
cout<<"LowResolutionDD"<<endl;
}
};
class HighResolutionDD:public DisplayDriver{
public:
void display(){
cout<<"HighResolutionDD"<<endl;
}
};
/* Print Driver Hierarchy */
class PrintDriver{
public:
PrintDriver(){}
virtual void print(){}
};
class LowResolutionPD:public PrintDriver{
public:
void print(){
cout<<"LowResolutionPD"<<endl;
}
};
class HighResolutionPD:public PrintDriver{
public:
void print(){
cout<<"HighResolutionPD"<<endl;
}
};
/* abstract factory */
class AbsFactory{
public:
virtual DisplayDriver* CreateDisplayDriver()=0;
virtual PrintDriver* CreatePrintDriver()=0;
};
/* Concrete factory1 */
class ConcreteFactory1: public AbsFactory{
public:
DisplayDriver* CreateDisplayDriver(){ return new HighResolutionDD; }
PrintDriver* CreatePrintDriver(){return new HighResolutionPD; }
};
/* Concrete factory2 */
class ConcreteFactory2: public AbsFactory{
public:
DisplayDriver* CreateDisplayDriver(){ return new LowResolutionDD; }
PrintDriver* CreatePrintDriver(){return new LowResolutionPD; }
};
int main(int argc, _TCHAR* argv[])
{
AbsFactory *factobj;
factobj = new ConcreteFactory2;
factobj->CreateDisplayDriver()->display();
factobj->CreatePrintDriver()->print();
}
As far as I can tell this is a correct factory. The decision to couple the
the display resolution capability with the printer resolution seems a bit
sketchy but could be enforced by other design considerations.
Your example implementation might be helped by giving the concrete
factory classes more descriptive names and selecting a concrete
factory based on a command line parameter:
int main(int argc, char* argv[])
{
AbsFactory *factobj;
if ( argc > 1 && 'H' == argv[1][0] )
{
factobj = new HighResFactory;
}
else
{
factobj = new LowResFactory;
}
factobj->CreateDisplayDriver()->display();
factobj->CreatePrintDriver()->print();
}
Antoon
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]