2 回答
TA贡献2041条经验 获得超4个赞
您的要求似乎与抽象工厂 GoF模式非常匹配,因为一旦您创建了一个具体工厂并且您的代码仅通过该工厂实例化客户端和解析器,就不可能错误地获得一组不匹配的客户端/解析器实例。
这AbstractFactory
是您的客户端用来实例化客户端/解析器对的对象:
interface AbstractFactory {
APIParser createAPIParser();
APIClient createAPIClient();
}
interface APIParser {}
interface APIClient {}
具体工厂可以提供匹配对(您可以重用产品实例,但我保持简单):
class ConcreteFactoryA implements AbstractFactory {
public APIParser createAPIParser() { return new APIParserA(); }
public APIClient createAPIClient() { return new APIClientA(); }
}
class ConcreteFactoryB implements AbstractFactory {
public APIParser createAPIParser() { return new APIParserB(); }
public APIClient createAPIClient() { return new APIClientB(); }
}
为了完整起见,这里是具体产品的声明:
class APIParserA implements APIParser {}
class APIParserB implements APIParser {}
class APIClientA implements APIClient {}
class APIClientB implements APIClient {}
示例客户端代码:
AbstractFactory factory = new ConcreteFactoryA();
APIClient client = factory.createAPIClient();
APIParser parser = factory.createAPIParser();
TA贡献1829条经验 获得超4个赞
你可以做的是在你的类中添加一个类型参数。
// wrapper for your json
public class APIResult<T extends APIClient<T>> {
private final String json;
public APIResult(String json) {
this.json = json;
}
public String getJson() {
return this.json;
}
}
// client always returns a result with itself as a type
public interface APIClient<T extends APIClient<T>> {
APIResult<T> makeRequest();
}
// parser only handles the implementation specific results of one client
public interface APIParser<T extends APIClient<T>> {
String getTemperature(APIResult<T> result);
}
public class APIClientA implements APIClient<APIClientA> {
public APIResult<APIClientA> makeRequest() {
// must return a result with this type
}
}
public class APIParserA implements APIParser<APIClientA> {
public String getTemperature(APIResult<APIClientA> result) {
// only accepts results from one specific client
}
}
添加回答
举报