如何更好地实现以下打字稿代码?

时间:2017-06-25 10:08:44

标签: typescript design-patterns factory

我有以下的typescript代码,它实现了请求 - 响应流程。

可以有两种类型的DataRequest - FooDataRequest& BarDataRequest。

这些请求类型有多个解析器。 FooResolver做Foo特定事情并发回FooDataResponse和BarResolver,它执行Bar特定的事情并发送回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);

实施旋转变压器工厂的最佳方法是什么?如果我有100个请求类型,那么if将有多个if else语句来标识适当的解析器。 或者有更好的方法来设计这个问题吗?

1 个答案:

答案 0 :(得分:0)

关注@plalx评论,这是一个例子:

class ResolverFactory {
    private static readonly resolvers: Map<typeof DataRequest, DataResolver> = new Map([
        [FooDataRequest, new FooViewResolver()],
        [BarDataRequest, new BarViewResolver()]
    ]);

    public static getResolver(request: DataRequest): DataResolver {
        let resolver: DataResolver | undefined = ResolverFactory.resolvers.get(request.type);
        if (!resolver) {
            throw new Error(`Resolver for '${String(request.type)}' not found`);
        }
        return resolver;
    }
}