|
| 1 | +class Singleton { |
| 2 | + constructor() { |
| 3 | + if (Singleton.instance) { |
| 4 | + return Singleton.instance; |
| 5 | + } |
| 6 | + this.data = "Singleton instance data"; |
| 7 | + Singleton.instance = this; |
| 8 | + return this; |
| 9 | + } |
| 10 | + |
| 11 | + getData() { |
| 12 | + return this.data; |
| 13 | + } |
| 14 | + |
| 15 | + static getInstance() { |
| 16 | + if(!Singleton.instance) { |
| 17 | + Singleton.instance = new Singleton(); |
| 18 | + } |
| 19 | + return Singleton.instance; |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +const instance1 = Singleton.getInstance(); |
| 24 | +console.log(instance1.getData()); |
| 25 | + |
| 26 | +const instance2 = new Singleton(); |
| 27 | +console.log(instance1 === instance2); |
| 28 | + |
| 29 | +// Extra Exercise // |
| 30 | + |
| 31 | +class UserSession { |
| 32 | + constructor() { |
| 33 | + if (UserSession.instance) { |
| 34 | + return UserSession.instance; |
| 35 | + } |
| 36 | + this.user = null; |
| 37 | + UserSession.instance = this; |
| 38 | + return this; |
| 39 | + } |
| 40 | + |
| 41 | + static getInstance() { |
| 42 | + if (!UserSession.instance) { |
| 43 | + UserSession.instance = new UserSession(); |
| 44 | + } |
| 45 | + return UserSession.instance; |
| 46 | + } |
| 47 | + |
| 48 | + setUser(id, username, name, email) { |
| 49 | + this.user = { id, username, name, email }; |
| 50 | + } |
| 51 | + |
| 52 | + getUser() { |
| 53 | + if (!this.user) { |
| 54 | + return "There is no user in the session" |
| 55 | + } |
| 56 | + return this.user; |
| 57 | + } |
| 58 | + |
| 59 | + clearSession() { |
| 60 | + this.user = null; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +const session1 = UserSession.getInstance(); |
| 65 | +session1.setUser(1, "Sac", "Isaac", "[email protected]"); |
| 66 | +console.log(session1.getUser()); |
| 67 | + |
| 68 | +const session2 = UserSession.getInstance(); |
| 69 | +console.log(session1 === session2); |
| 70 | + |
| 71 | +session2.clearSession(); |
| 72 | +console.log(session1.getUser()); |
0 commit comments