-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFactoryMethodPattern.js
More file actions
89 lines (75 loc) · 1.94 KB
/
Copy pathFactoryMethodPattern.js
File metadata and controls
89 lines (75 loc) · 1.94 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
"use strict";
/**
* Factory Method Pattern - A pattern which uses sub classes to generate an
* object. This pattern can be considered a more advanced version of the
* Simple Factory Pattern but it delegates the creation of components to
* the subclasses
*
* Example - The Super Administrator is considered the Creator in the application
* He/she is able to create an administrator account, an editor account or just
* a normal user account
*
* In this example I use npm:prompt to get user input
*/
var prompt = require("prompt");
class SuperAdministrator {
// SuperAdministrator provides an interface
createUser() {
}
}
class AdminCreator extends SuperAdministrator {
createUser() {
return new Admin();
}
}
class EditorCreator extends SuperAdministrator {
createUser() {
return new Editor();
}
}
class UserCreator extends SuperAdministrator {
createUser() {
return new User();
}
}
class User {
constructor(privileges) {
//Default CanView
this.privileges = ["CanView"];
if(privileges) {
this.privileges = this.privileges.concat(privileges)
}
}
getPrivileges() {
return this.privileges;
}
}
class Admin extends User {
constructor() {
super(["CanCreate", "CanEdit"])
}
}
class Editor extends User {
constructor() {
super(["CanEdit"])
}
}
prompt.start();
let user;
prompt.get([{
name: "userType",
description: `What kind of user do you wish to create? ["admin", "editor", "normal"]`,
required: true
}], function(err, result) {
let userType = result.userType;
let userFactory;
if (userType == "admin") {
userFactory = new AdminCreator();
} else if (userType == "editor") {
userFactory = new EditorCreator();
} else {
userFactory = new UserCreator();
}
user = userFactory.createUser();
console.log(user.getPrivileges());
})