Skip to content

Instantly share code, notes, and snippets.

@tuanna-hsp
Last active December 15, 2021 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuanna-hsp/c537f51492f533b69dd62a21e6669365 to your computer and use it in GitHub Desktop.
Save tuanna-hsp/c537f51492f533b69dd62a21e6669365 to your computer and use it in GitHub Desktop.
Factory class example
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