I'm working on an app where we need to use different authentication flows depending on how the user is accessing the app. I want to make sure that there is only one instance of the authentication service at a given time (singleton).
There aren't that many auth services types and I don't expect there to be more than 3-4 types in the future.
Here are the two approaches that I can think of:
Approach A (Factory pattern):
export class AuthFactory {
public instance
public getInstance(): AuthService {
if (this.instance) {
return this.instance
} else {
this.instance = fooConditon ? new authServiceA() : new authServiceB()
return this.instance
}
}
}
export abstract class AuthService {
...
}
export class AuthServiceA implements AuthService {
...
}
export class AuthServiceB implements AuthService {
...
}
Approach B
Completely skip the factory and have a getInstance()
method inside the abstract class
export abstract class AuthService {
public instance
public getInstance(): AuthService {
if (this.instance) {
return this.instance
} else {
this.instance = fooConditon ? new authServiceA() : new authServiceB()
return this.instance
}
}
...
}
export class AuthServiceA implements AuthService {
...
}
export class AuthServiceB implements AuthService {
...
}
Which approach is better and why? For me, I feel like having the factory is overkill because there are very few sub classes of AuthService
but I wonder if I'm overlooking something.
I was also wondering, if the factory approach is the way to go, is creating a singleton factory (one that only creates one instance of the product sub classes and not one of each product subclass) common? Is there a better way to do it?
AuthService::getInstance
to be non-static? At the moment you need anAuthService
to get anAuthService