-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandfactory.cpp
More file actions
68 lines (59 loc) · 1.85 KB
/
Copy pathcommandfactory.cpp
File metadata and controls
68 lines (59 loc) · 1.85 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
// A command factory class to create new instances of command objects.
//
// Assumptions:
// -- Each command will have a unique char identifier
//
// Implementation:
// -- character case is handled by the hash
//---------------------------------------------------------------------------
#include "commandfactory.h"
#include "checkout.h"
#include "display.h"
#include "history.h"
#include "return.h"
//---------------------------------------------------------------------------
// commandFactory()
CommandFactory::CommandFactory() {
// Checkout, display, Return, History
commandTypes[2] = new Checkout;
commandTypes[3] = new Display;
commandTypes[7] = new History;
commandTypes[17] = new Return;
}
//---------------------------------------------------------------------------
// destructor()
CommandFactory::~CommandFactory() {
for (int i = 0; i < ALPHABET; i++) {
if (commandTypes[i] != nullptr) {
delete commandTypes[i];
commandTypes[i] = nullptr;
}
}
}
//---------------------------------------------------------------------------
// createCommand()
Command *CommandFactory::createCommand(char type) {
if (type < 'A' || type > 'z') {
return nullptr;
}
// create new command pointer
Command *toReturn = nullptr;
// create subscript from hash
int subscript = hash(type);
// if command exists at hash location
if (subscript > 0 && commandTypes[subscript] != nullptr) {
toReturn = commandTypes[subscript]->create();
}
return toReturn;
}
//---------------------------------------------------------------------------
// hash
int CommandFactory::hash(char type) const {
int subscript = 0;
if (type > 'A' && type < 'z') {
// change to uppercase if it's not
type = toupper(type);
subscript = type - 'A';
}
return subscript;
}