-
Notifications
You must be signed in to change notification settings - Fork 0
/
The Factory Pattern
61 lines (47 loc) · 1.74 KB
/
The Factory Pattern
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
Say that I need a user object. I can create one:
var user1 = {
name: "Adam Zerner",
email: "[email protected]",
password: "password"
};
Now say that I want to create a few more users. I could do that:
var user2 = {
name: "John Smith",
email: "[email protected]",
password: "12345"
};
var user3 = {
name: "Greg Popovich",
email: "[email protected]",
password: "rings"
};
var user4 = {
name: "Ike Taylor",
email: "[email protected]",
password: "swag"
};
Phew, that was a little exhausting. These objects all have the same properties
(name, email and password). Maybe I could write a function to do the work for me.
But how would I do that?
Well, let's see. I want the function to return an object that has those three
properties. And I want to set the properties to the arguments of the function.
How about something like this:
function makeUser(name, email, password) {
var toRet = {};
toRet.name = name;
toRet.email = email;
toRet.password = password;
return toRet;
}
Now I could do something like this:
var user1 = makeUser("Adam Zerner", "[email protected]", "password");
var user2 = makeUser("John Smith", "[email protected]", "12345");
var user3 = makeUser("Greg Popovich", "[email protected]", "rings");
var user4 = makeUser("Ike Taylor", "[email protected]", "swag");
Pretty cool! That's a lot simpler and more concise than lines 3-27.
This is called the factory pattern because our makeUser function is sort of
like a factory for making users.
==============================================================================
See https://github.com/adamzerner/articles/blob/master/The%20%22new%22%20keyword
for info on how we could use classes and the new keyworkd to implement the factory
pattern a bit differently.