I have following typescript code which implements a request-response flow.
There can be two types of DataRequest - FooDataRequest & BarDataRequest .
There are multiple resolvers for these request types . FooResolver does Foo specific things and sends back FooDataResponse and BarResolver which does Bar specific things and send back BarDataResponse
abstract class DataRequest{
public type: typeof DataRequest;
public payload: string;
}
abstract class DataResponse {
public data: any;
}
class FooDataRequest extends DataRequest {
constructor() {
super();
this.type = FooDataRequest;
this.payload = "foo request";
}
}
class BarDataRequest extends DataRequest {
constructor() {
super();
this.type = FooDataRequest;
this.payload = "foo request";
}
}
class FooDataResponse extends DataResponse {
constructor() {
super();
this.data = "foo response";
}
}
class BarDataResponse extends DataResponse {
constructor() {
super();
this.data = "bar response";
}
}
abstract class DataResolver {
abstract resolve(request:DataRequest): DataResponse
}
class FooViewResolver extends DataResolver {
public resolve(reportRequest:FooDataRequest): FooDataResponse {
return new FooDataResponse();
}
}
class BarViewResolver extends DataResolver {
public resolve(dashboardRequest:BarDataRequest): BarDataResponse {
return new BarDataResponse();
}
}
class ResolverFactory {
public static getResolver(request: DataRequest): DataResolver {
//If there is 100 request , then so many if else statement
//That is not effective
if (request.type === FooDataRequest) {
return new FooViewResolver();
}
else if (request.type = BarDataRequest) {
return new BarViewResolver();
}
}
}
const request :DataRequest = new FooDataRequest();
const resolver: DataResolver = ResolverFactory.getResolver(request);
console.log(resolver);
const response: DataResponse = resolver.resolve(request);
console.log(response);
What is the best method to implement a resolver factory? If i have 100 request types then if will have multiple if else statements to identify appropriate resolver. Or is there a better way to design this problem?
Aucun commentaire:
Enregistrer un commentaire