Last active
November 5, 2022 16:16
-
-
Save Teebo/0ed4cec8386962662a1c557f411efcd6 to your computer and use it in GitHub Desktop.
Singleton pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface ISession { | |
username: string; | |
token: string; | |
} | |
/** | |
* Session class | |
*/ | |
export class Session implements ISession { | |
private static instance: Session; | |
public username: string; | |
public _token: string; | |
private constructor(session: ISession) { | |
this.username = session.username; | |
this._token = session.token; | |
} | |
set token(token: string) { | |
this._token = token; | |
} | |
get token(): string { | |
return this._token; | |
} | |
/** | |
* | |
* @param session An object of type ISession | |
* @returns A session instance | |
*/ | |
static createSession(session: ISession): Session { | |
if(this.instance) { | |
console.error(`You tried to create another session instance...returning the existing one..\n`); | |
return this.instance; | |
} | |
this.instance = new Session(session); | |
return this.instance; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a session instance | |
const session = Session.createSession({token: 'jwt', username: 'User1'}); | |
// Create another session instance | |
const session2 = Session.createSession({token: 'jwt2', username: 'User2'}); // Cannot instantiate another session. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment