到目前为止,我有一个名为RestClient的rest客户端,它实现了一个名为IRestClient的接口。在整个代码中,我在声明其余客户端时使用IRestClient。但是在几个地方,我使用new运算符创建了客户端。因此,如果我想将客户端更改为NewRestClient,则必须遍历我的代码并找到创建客户端的所有位置。
解决这个问题的好方法是什么?像下面这样的工厂班还可以吗?
class RestClientFactory
{
public static IRestClient create()
{
return new RestClient();
}
}
那样的话,我只有一个地方可以将RestClient()更改为NewRestClient()。
仅当您希望/需要IRestClient
基于某些参数提供确切的实现时,才需要使用工厂方法模式。由于这似乎不是您的情况,因此通过面向interfaces进行编程会很好。所以,不要这样:
RestClient restClient = new RestClient();
restClient.foo("bar");
您将拥有:
//declare the variable as interface
//assign the value with the class implementation
IRestClient restClient = new RestClient();
restClient.foo("bar");
因此,如果您需要一个新的实现,只需将当前实现更改为所需的实现即可:
IRestClient restClient = new FooRestClient();
//rest of the code remains intact
restClient.foo("bar");
如果要将其移入Factory Method Pattern,则将具有以下内容:
class RestClientFactory {
public static IRestClient defaultRestClient() {
return new RestClient();
}
public static IRestClient createRestClient(String name) {
String realName = name.toLowerCase();
switch(realName) {
case "foo":
return new FooRestClient();
case "bar":
return new BarRestClient();
//and on...
default:
return defaultRestClient();
}
}
}
然后,您必须通过从工厂调用相应的方法来初始化实例:
IRestClient restClient = RestClientFactory.createRestClient("foo");
//rest of the code remains intact
restClient.foo("bar");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句