Repository navigation
Expand file tree
/
Copy pathflyweight_bookfactory.html
More file actions
92 lines (82 loc) · 2.33 KB
/
Copy pathflyweight_bookfactory.html
File metadata and controls
92 lines (82 loc) · 2.33 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Basic Factory Pattern Example</title>
</head>
<body>
<h1>Basic Factory Pattern Example</h1>
<button id="createButton">Create Book</button>
<div id="output"></div>
<script>
// Book class representing individual books
class Book {
constructor({ title, author, genre, pageCount, publisherID, ISBN }) {
this.title = title;
this.author = author;
this.genre = genre;
this.pageCount = pageCount;
this.publisherID = publisherID;
this.ISBN = ISBN;
}
getTitle() {
return this.title;
}
getAuthor() {
return this.author;
}
getISBN() {
return this.ISBN;
}
}
// Book Factory Singleton
const existingBooks = {};
class BookFactory {
createBook({ title, author, genre, pageCount, publisherID, ISBN }) {
const existingBook = existingBooks[ISBN];
if (!!existingBook) {
return existingBook;
} else {
const book = new Book({
title,
author,
genre,
pageCount,
publisherID,
ISBN,
});
existingBooks[ISBN] = book;
return book;
}
}
}
// Button click event
const createButton = document.getElementById('createButton');
createButton.addEventListener('click', function () {
createBook();
});
// Create a new book
function createBook() {
const bookFactory = new BookFactory();
const bookData = {
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
genre: 'Classic',
pageCount: 180,
publisherID: 'Penguin',
ISBN: '978-0141182636',
};
const book = bookFactory.createBook(bookData);
const output = document.getElementById('output');
output.innerHTML = `
<h3>Book Created</h3>
<ul>
<li><strong>Title:</strong> ${book.getTitle()}</li>
<li><strong>Author:</strong> ${book.getAuthor()}</li>
<li><strong>ISBN:</strong> ${book.getISBN()}</li>
</ul>
`;
}
</script>
</body>
</html>