Factory Class Pattern

Is this how you do a factory pattern? Im curious to learn since it will make my design a little easier to scale. My code is still a work in progress but I just wanted to ask before i get too far.

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#include <iostream>
#include <string>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>

std::mt19937 mt{ static_cast<unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count()) };

class Trait
{
	public:
		Trait(const std::string& name, const std::string& description) : 
			mName(name), mDescription(description)
		{}

		std::string GetName() const
		{
			return mName;
		}

		std::string GetDescription() const
		{
			return mDescription;
		}

	private:
		std::string mName{ "Trait Name" };
		std::string mDescription{ "Trait Description" };
};

class Effect
{
	public:
		Effect(const std::string& name, const std::string& description) : 
			mName(name), mDescription(description)
		{}

	private:
		std::string mName{ "Effects" };
		std::string mDescription{ "Effect Description" };
	};

	class BodyPart
	{
	public:
		BodyPart(const std::string& name, int hitPoints) : 
			mName(name), mHitPoints(hitPoints)
		{}

		std::string GetName() const
		{
			return mName;
		}

		int GetHitPoints() const
		{
			return mHitPoints;
		}

		void ApplyEffect(const Effect& effect)
		{
			mEffects.push_back(effect);
		}

	private:
		std::string mName{ "Body Part Name" };
		int mHitPoints{ 0 };

		std::vector<Effect> mEffects;
};

class Colonist
{
	public:
		Colonist(const std::string& firstName, const std::string& lastName, int biologicalAge, int chronologicalAge) :
			mFirstName(firstName), mLastName(lastName), mBiologicalAge(biologicalAge), mChronologicalAge(chronologicalAge)
		{}

		std::string GetFirstName() const
		{
			return mFirstName;
		}

		std::string GetLastName() const
		{
			return mLastName;
		}

		int GetBiologicalAge() const
		{
			return mBiologicalAge;
		}

		int GetChronologicalAge() const
		{
			return mChronologicalAge;
		}

		void AddTrait(const Trait& trait)
		{
			auto compare = [&trait](const Trait& a)
			{
				return a.GetName() == trait.GetName();
			};

			auto it = std::find_if(mTraits.begin(), mTraits.end(), compare);
			if (it == mTraits.end())
			{
				mTraits.push_back(trait);
			}
		}

		std::vector<Trait> GetTraits() const
		{
			return mTraits;
		}

		void AddBodyPart(const BodyPart& bodyPart)
		{
			auto compare = [&bodyPart](const BodyPart& a)
			{
				return a.GetName() == bodyPart.GetName();
			};

			auto it = std::find_if(mBodyParts.begin(), mBodyParts.end(), compare);
			if (it == mBodyParts.end())
			{
				mBodyParts.push_back(bodyPart);
			}
		}

		std::vector<BodyPart> GetBodyParts() const
		{
			return mBodyParts;
		}

	private:
		std::string mFirstName{ "Colonist First Name" };
		std::string mLastName{ "Colonist Last Name" };
		int mBiologicalAge{ 0 };
		int mChronologicalAge{ 0 };

		std::vector<Trait> mTraits;
		std::vector<BodyPart> mBodyParts;
};

class ColonistFactory 
{
	public:
		ColonistFactory(const std::vector<std::string>& firstNames, const std::vector<std::string>& lastNames, const std::vector<Trait>& traits, const std::vector<BodyPart>& bodyParts)
			: mFirstNames(firstNames), mLastNames(lastNames), mTraits(traits), mBodyParts(bodyParts)
		{}

		Colonist CreateRandomColonist() 
		{
			std::uniform_int_distribution<int> chooseRandomFirstName(0, mFirstNames.size() - 1);
			std::uniform_int_distribution<int> chooseRandomLastName(0, mLastNames.size() - 1);
			std::uniform_int_distribution<int> randomBiologicalAge(17, 100);
			std::uniform_int_distribution<int> randomChronologicalAge(0, 5447);
			std::uniform_int_distribution<int> randomTrait(0, mTraits.size() - 1);

			int firstNameIndex = chooseRandomFirstName(mt);
			int lastNameIndex = chooseRandomLastName(mt);
			int biologicalAge = randomBiologicalAge(mt);
			int chronologicalAge = randomChronologicalAge(mt);

			Colonist colonist(mFirstNames[firstNameIndex], mLastNames[lastNameIndex], biologicalAge, chronologicalAge);

			for (int i = 0; i < 3; ++i) 
			{
				colonist.AddTrait(mTraits[randomTrait(mt)]);
			}

			for (const auto& part : mBodyParts) 
			{
				colonist.AddBodyPart(part);
			}

			return colonist;
		}

	private:
		std::vector<std::string> mFirstNames;
		std::vector<std::string> mLastNames;
		std::vector<Trait> mTraits;
		std::vector<BodyPart> mBodyParts;
};


int main()
{
	// Initialization of data
	std::vector<std::string> firstNames
	{
		"Amanda",
		"Alex",
		"Alexis",
		"Alexa",
		"Angela",
		"Anna",
		"Brittany",
		"Blaine",
		"Brian",
		"Barney",
		"Betty",
		"Bob",
		"Chad",
		"Chelsea",
		"Chester",
		"Charlene",
		"David",
		"Donald",
		"Dorothy",
		"Destiny",
		"Dwayne"
	};

	std::vector<std::string> lastNames
	{
		"Hawkins",
		"Stevens",
		"Jacobson",
		"Karlson",
		"Benett",
		"Wilks",
		"Anders",
		"Peterson",
		"White",
		"Park",
		"Lee",
		"Johnson",
		"Chin",
		"Nguyen",
		"Farr",
		"Galigher",
		"Gold",
		"Goldman",
		"Lutess",
		"Kaltritter"
	};

	std::vector<BodyPart> bodyParts
	{
		BodyPart("Head", 100),
		BodyPart("Left Arm", 100),
		BodyPart("Right Arm", 100),
		BodyPart("Left Leg", 100),
		BodyPart("Right Leg", 100),
		BodyPart("Torso", 100)
	};

	std::vector<Trait> traitList
	{
		Trait{ "Lazy", "Hates work" },
		Trait{ "Hard Worker", "Will help other colonists willfully." },
		Trait{ "Alcoholic", "This colonist will consume far more alcohol than others." },
		Trait{ "Psychopath", "This colonist has no empathy for others or remorse for doing bad things" },
		Trait{ "Night Owl", "This colonist loves to be up at night" },
		Trait{ "Gourmand", "This colonists life revolves around food" },
		Trait{"Greedy", "This colonist tends to take more than they need."},
		Trait{"Jealous", "This coilonist hates it when anyone else has things they want"},
		Trait{"Pyromaniac", "This colonist loves to set fires."}
	};

	const int mCurrentYear{ 7423 };

	const int maxColonists{ 20 };

	std::vector<Colonist> mColonistRoster;

	// Using the factory
	ColonistFactory factory(firstNames, lastNames, traitList, bodyParts);

	for (int i = 0; i < maxColonists; i++) 
	{
		mColonistRoster.push_back(factory.CreateRandomColonist());
	}

	for (const auto& colonist : mColonistRoster)
	{
		std::cout << "Info:\n";
		std::cout << "   " << colonist.GetFirstName() << " " << colonist.GetLastName() << " - " << colonist.GetBiologicalAge() << " (" << colonist.GetChronologicalAge() << ") - Born " << mCurrentYear - colonist.GetChronologicalAge() << " years ago.\n";

		const auto& bodyParts = colonist.GetBodyParts();

		std::cout << '\n' << colonist.GetFirstName() << "'s Body Parts:\n";
		for (const auto& part : bodyParts)
		{
			std::cout << "  -" << part.GetName() << " (" << part.GetHitPoints() << ")\n";
		}

		std::cout << '\n' << colonist.GetFirstName() << "'s Traits:\n";
		for (const auto& trait : colonist.GetTraits())
		{
			std::cout << "  -" << trait.GetName() << " - " << trait.GetDescription() << '\n';
		}

		std::cout << '\n';
	}
}
Last edited on
Normally a factory is used to create objects of derived classes/types according to some input.
But since the definition of that pattern is not that strict I think your version can be considered as a factory pattern.
Typically, a "factory" pattern would look like this:

Common interfaces:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class IFoo
{
public:
    virtual void foo(void) = 0;
    virtual ~IFoo() {}
};

class IBar
{
public:
    virtual void bar(void) = 0;
    virtual ~IBar() {}
};

class IFactory
{
public:
    virtual IFoo *createFoo(void) const = 0;
    virtual IBar *createBar(void) const = 0;
    virtual ~IFactory() {}
};

A concrete implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyFoo : public IFoo
{
public:
    virtual void foo(void) { std::cout << "Hello, from MyFoo::foo()!" << std::endl; }
    virtual ~MyFoo() { std::cout << "MyFoo: Bye-bye!" << std::endl; }
};

class MyBar : public IBar
{
public:
    virtual void bar(void) { std::cout << "Hello, from MyBar::bar()!" << std::endl; }
    virtual ~MyBar() { std::cout << "MyBar: Bye-bye!" << std::endl; }
};

class MyFactory : public IFactory
{
public:
    virtual IFoo* createFoo(void) const { return new MyFoo(); }
    virtual IBar* createBar(void) const { return new MyBar(); }
};

Usage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void test(const IFactory *const someFactory)
{
    IFoo *const someFoo = someFactory->createFoo();
    someFoo->foo();

    IBar *const someBar = someFactory->createBar();
    someBar->bar();

    delete someFoo;
    delete someBar;
}

int main()
{
    MyFactory theFactory;
    test(&theFactory);
}


Note how test() has/needs absolutely no knowledge about the concrete implementations!
Last edited on
Typically, a factory comes in play when you have inheritance and the objects differ by just one or two properties.

Consider an example for a school with Students, Teachers, Admin then we can have something like this.

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
enum class UserType {
    STUDENT, 
    TEACHER,
    ADMIN
}
class User {
    private:
    std::string name;
    UserType type; 
    // other properties

    public:
      User(UserType type, const std::string &name, /*Other possible params*/);

    virtual void performAction() = 0;
}

class Student: public User{
    private: 
    // student-specific props

    public:
      Student(const std::string &name)
        : User(UserType::STUDENT, name){}

    virtual void performAction() override {/*concrete action*/}
}

class Teacher: public User{
    private: 
    // student-specific props

    public:
      Teacher(const std::string &name)
        : User(UserType::TEACHER, name){}

    virtual void performAction() override {/*concrete action*/}
}


class Admin: public User{
    private: 
    // student-specific props

    public:
      Admin(const std::string &name)
        : User(UserType::ADMIN, name){}

    virtual void performAction() override {/*concrete action*/}
}



class UserFactor {
    public:
    // can be unique_ptr or shared_ptr or raw pointer (not adviceable on modern C++ projects)
    static std::unique_ptr<User> create(UserType userType, const std::string &name){
        switch (userType) {
        case UserType::STUDENT:
            return std::make_unique<Student>(name);
        case UserType::TEACHER:
            return std::make_unique<Teacher>(name);
        case UserType::ADMIN:
             return std::make_unique<Admin>(name);
        // If tomorrow you have more user types in your system, just a case here
        default:
            return nullptr;
        }
    }
}


int main(){

// create a student
    auto student = UserFactor::create(UserType::STUDENT, "Awesome Name");
    // std::unique_ptr<Student> user = UserFactor::create(UserType::STUDENT, "Awesome Name");
    student->performAction();

    auto teacher = UserFactor::create(UserType::TEACHER, "Teacher name");
    teacher->performAction();
    return 0;
}

Last edited on
Topic archived. No new replies allowed.