Last active
December 15, 2021 04:13
-
-
Save tuanna-hsp/c537f51492f533b69dd62a21e6669365 to your computer and use it in GitHub Desktop.
Factory class example
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
class AggregationService { | |
constructor(private readonly clientFactory: AggregationClientFactory) {} | |
public processRequest(request: AggregationRequest): void { | |
const client = this.clientFactory.createClient(request.serviceName); | |
if (request.type === "getAccounts") { | |
const result = client.getAccounts(); | |
// Save result | |
} | |
if (request.type === "getBillings") { | |
const result = client.getBillings(); | |
// Save result | |
} | |
} | |
} | |
// | |
// Factory | |
// | |
class AggregationClientFactory { | |
nameToClientMap = { | |
"GitHub": GitHubClient, | |
"Discord": DiscordClient, | |
} | |
public createClient(name: String): AbstractAggregationClient { | |
const clientClass = this.nameToClientMap[name]; | |
const clientOptions: ClientOptions = { | |
logger: this.createLogger(), | |
httpService: this.httpService, | |
}; | |
return new clientClass(clientOptions); | |
} | |
} | |
// | |
// Clients | |
// | |
abstract class AbstractAggregationClient { | |
constructor(private readonly options) {} | |
public getAccounts(): AggregationResult {} | |
public getBillings(): AggregationResult {} | |
} | |
class GitHubClient extends AbstractAggregationClient { | |
public getAccounts(): AggregationResult { | |
// GitHub getAccounts logic | |
} | |
} | |
class DiscordClient extends AbstractAggregationClient { | |
public getAccounts(): AggregationResult { | |
// Discord getAccounts logic | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment