|
4 | 4 | * [Abstract Factory](#abstract-factory)
|
5 | 5 | * [Builder](#builder)
|
6 | 6 | * [Factory Method](#factory-method)
|
| 7 | +* [Prototype](#prototype) |
| 8 | +* [Singleton](#singleton) |
7 | 9 |
|
8 | 10 |
|
9 | 11 |
|
@@ -77,7 +79,7 @@ class ApiRequestFactory {
|
77 | 79 | const availableOptions = ["tcp", "http"];
|
78 | 80 | const apiRequest = ApiRequestFactory.createApiRequest(availableOptions[Math.floor(Math.random() * 2)]);
|
79 | 81 | apiRequest.makeGetRequest("example.com")
|
80 |
| - .then(respone => console.log(respone)) |
| 82 | + .then(response => console.log(response)) |
81 | 83 | .catch(err => console.log(err));
|
82 | 84 | ```
|
83 | 85 |
|
@@ -234,5 +236,60 @@ let c = new ClientHTTP;
|
234 | 236 | c.main();
|
235 | 237 | ```
|
236 | 238 |
|
| 239 | +### Prototype |
| 240 | +##### prototype.js |
| 241 | +```Javascript |
| 242 | +class Server { |
| 243 | + |
| 244 | + constructor(port) { |
| 245 | + this._port = port; |
| 246 | + } |
| 247 | + listen() { |
| 248 | + console.log("Listening on port"); |
| 249 | + } |
| 250 | + clone() { |
| 251 | + return new Server(this._port); |
| 252 | + } |
| 253 | +} |
| 254 | + |
| 255 | +const server = new Server(); |
| 256 | +const newServer = server.clone(); |
| 257 | +newServer.listen(); |
| 258 | +``` |
| 259 | + |
| 260 | +### Singleton |
| 261 | +##### singleton.js |
| 262 | +```Javascript |
| 263 | +class Server { |
| 264 | + constructor(port) { |
| 265 | + this._port = port; |
| 266 | + } |
| 267 | + static init(port) { |
| 268 | + if (typeof Server.instance === 'object') { |
| 269 | + return Server.instance; |
| 270 | + } |
| 271 | + Server.instance = new Server(port); |
| 272 | + return Server.instance; |
| 273 | + } |
| 274 | + static getInstance() { |
| 275 | + if (typeof Server.instance === 'object') { |
| 276 | + return Server.instance; |
| 277 | + } |
| 278 | + Server.instance = new Server(8080); |
| 279 | + return Server.instance; |
| 280 | + } |
| 281 | + status() { |
| 282 | + console.log("Server listening on port " + this._port); |
| 283 | + } |
| 284 | +} |
| 285 | + |
| 286 | +/** |
| 287 | + * Client calls init, and getInstance would give that instance |
| 288 | + * always. Singleton is used for heavy single use objects like DB |
| 289 | + */ |
| 290 | +Server.init(1234); |
| 291 | +Server.getInstance().status(); |
| 292 | +``` |
| 293 | + |
237 | 294 |
|
238 | 295 |
|
0 commit comments