The name of pattern is Strategy. In addition, it is necessary to use Factory method pattern to resolve request instances of strategies.
You can choose any strategy at the runtime based on your parameter.
Let me show an example of implementation via TypeScript. So we need some request types:
type RequestStrategyType = 'axios' | 'superagent' | 'fetch';
And some abstractions that can be implemented by request strategies:
interface RequestStrategy {
name: RequestStrategyType;
fetch: () => any;
}
abstract class BaseRequestStrategy implements RequestStrategy {
constructor(public name: RequestStrategyType) { }
fetch() {
return `fetched by BaseRequestStrategy`;
}
}
And its concrete implementations:
class AxiosRequestStrategy extends BaseRequestStrategy {
constructor() {
super('axios');
}
fetch() {
return `fetched by AxiosRequestStrategy`;
}
}
class SuperagentRequestStrategy extends BaseRequestStrategy {
constructor() {
super('superagent');
}
fetch() {
return `fetched by SuperagentRequestStrategy`;
}
}
class FetchRequestStrategy extends BaseRequestStrategy {
constructor() {
super('fetch');
}
fetch() {
return `fetched by FetchRequestStrategy`;
}
}
And it is necessary to implement Factory pattern to generate request strategies by RequestStrategyType
:
class RequestStrategyFactory {
create(type: RequestStrategyType) {
switch (type) {
case 'axios':
return new AxiosRequestStrategy();
case 'superagent':
return new SuperagentRequestStrategy();
case 'fetch':
return new FetchRequestStrategy();
default:
console.log(`The ${type} strategy is not available.
Falling back to default request strategy.`)
return new AxiosRequestStrategy();
}
}
}
And this is a class which works with RequestStrategyFactory
:
class RequestClient {
strategyFactory = new RequestStrategyFactory();
public make(strategyType: RequestStrategyType) {
return this.strategyFactory.create(strategyType);
}
}
And then code can be called like this:
const requestClient = new RequestClient();
const axiosClient = requestClient.make('axios');
console.log(`axiosClient`, axiosClient)
const superagentClient = requestClient.make('superagent');
console.log(`superagentClient`, superagentClient)
const fetchClient = requestClient.make('fetch');
console.log(`fetchClient`, fetchClient)