As
we discussed in last block 'what is meant by abstract factory design
pattern?'. In this block I am going to discussed about CPP example of Abstract
Factory Design Pattern.
The
main difference between factory design and abstract factory design is that in
factory design pattern construct single object and abstract factory construct
multiple object.Procedure for writing CPP code for Abstract Factory Design
Pattern is as follow:
- Create the abstract product
- Create the concrete product
- Create abstract factor
- Create concrete factories (with related/ dependent object)
- Create
client
Code for Book
example which we discussed in last block
#include
<iostream>
#define BIOGRAPHY
//define NOVEL
using namespace
std;
class Book //Create Abstract Product
{ public:
virtual void draw() = 0;
};
class BiographyPrice
: public Book //Create Concrete
product 1
{ public:
void draw() { cout <<
"Price:500\n"; }
};
class BiographyAuthor
: public Book
{ public:
void draw() { cout << "Author:
Arun Tiwari\n"; }
};
class NovelPrice
: public Book //Create
Concrete product 2
{public:
void draw() { cout <<
"Price:600\n"; }
};
class NovelAuthor
: public Book
{ public:
void draw() { cout << "Author:
Henry Fielding\n"; }
};
class Factory //Create Abstract Factory
{ public:
virtual Book *Price() = 0;
virtual Book *Author() = 0;
};
class BiographyFactory
: public Factory //Concrete
factory 1
{ public:
Book *Price() { return new BiographyPrice; }
Book *Author() { return new BiographyAuthor; }
};
class NovelFactory
: public Factory
//Concrete factory 2
{ public:
Book *Price() { return new NovelPrice; }
Book *Author() { return new NovelAuthor; }
};
class Client //Create client
{ private:
Factory *factory;
public:
Client(Factory *f)
{ factory = f; }
void draw()
{ Book *b = factory->Price();
b->draw();
display_window_one();
display_window_two();
}
void display_window_one()
{ Book *b[] = {
factory->Price(),
factory->Author()
};
b[0]->draw();
b[1]->draw();
}
void display_window_two()
{ Book *b[] =
{ factory->Price(),
factory->Author()
};
b[0]->draw();
b[1]->draw();
} };
int main()
{ Factory
*factory;
#ifdef BIOGRAPHY
factory = new BiographyFactory;
#else // NOVEL
factory = new NovelFactory;
#endif
Client *c = new Client(factory);
c->draw();
}
RESULT:
Link of Blog: https://drive.google.com/a/vit.edu/file/d/1MvcuWT7pAIlq19Hs102N4MwEGwnP1-3y/view?usp=drivesdk

