-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory_pattern.cpp
More file actions
96 lines (83 loc) · 1.81 KB
/
factory_pattern.cpp
File metadata and controls
96 lines (83 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
Animal (string nam = "Who am I ?"):name(nam)
{
}
virtual void eat () {cout << name << " is Eating \n";}
virtual void sleep () {cout << name << " is Sleeping \n";}
virtual void speak () {}
virtual ~Animal () {cout << "Destroying Animal \n";}
protected:
string name;
};
class Cat : public Animal
{
public:
Cat ():Animal("cat") {}
// Over-rides the base implementation
void speak () {cout << "Meoow \n";}
~Cat () {cout << "Destroying cat \n";}
};
class Dog : public Animal
{
public:
Dog ():Animal("Dog") {}
void speak () {cout << name << ": Woof \n";}
~Dog () {cout << "Destroying Dog \n";}
};
class BullDog : public Dog
{
public:
BullDog () {name = "Bull Dog";}
void speak () {cout << name << ": Wrrrrrrrrroof \n";}
~BullDog () {cout << "Destroying Bull Dog \n";}
};
class AnimalFactory
{
public:
enum ANIMAL {
CAT,
DOG,
BULLDOG
};
static Animal * make_animal (ANIMAL choice)
{
switch (choice)
{
case CAT:
return new Cat ();
case DOG:
return new Dog ();
case BULLDOG:
return new BullDog ();
default:
throw ("Choice not defined");
}
}
static Animal * make_animal (string choice)
{
if (choice == "cat")
return new Cat ();
else if (choice == "dog")
return new Dog ();
else if (choice == "bulldog")
return new BullDog ();
else
throw ("Choice not defined");
}
};
int main ()
{
// Note that client is independent of the derived classes. Derived classes depend on implementation details
Animal *doggy = AnimalFactory::make_animal (AnimalFactory::DOG);
Animal *bullDoggy = AnimalFactory::make_animal ("bulldog");
doggy->speak ();
bullDoggy->speak ();
delete doggy;
delete bullDoggy;
cout << "Bye Bye " << endl;
}