我正在尝试实现从服务器获取 XML 文档的工厂模式。(使用 javax.xml.parsers.DocumentBuilder)
我现在有下面的课程,你能给出你的意见吗?这种结构对这种模式有意义吗?(我在 codereview 上问了同样的问题,但如果还没有任何反馈)
DocumentGeneratorFactory(抽象工厂)
public interface DocumentGeneratorFactory {
public Document createDocument(String scheme, String authority,
String path, HashMap<String, String> parameters)
throws ParserConfigurationException, SAXException, IOException;
}
ProductDocumentGeneratorFactory(创建工厂)
public class ProductDocumentGeneratorFactory implements
DocumentGeneratorFactory {
public Document createDocument(String scheme, String authority,
String path, HashMap<String, String> parameters)
throws ParserConfigurationException, SAXException, IOException {
Uri.Builder uri = new Uri.Builder();
uri.scheme(scheme);
uri.authority(authority);
uri.path(path);
Set<Map.Entry<String, String>> set = parameters.entrySet();
for (Map.Entry<String, String> params : set) {
uri.appendQueryParameter(params.getKey(), params.getValue());
}
URL url = new URL(uri.toString());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
return doc;
}
}
请求(抽象产品)
public abstract class Request {
Document doc;
HashMap<String, String> queryStrings;
abstract void prepareRequest() throws ParserConfigurationException, SAXException, IOException;
}
产品请求(产品)
public class ProductRequest extends Request{
ProductDocumentGeneratorFactory DocumentGeneratorFactory;
HashMap<String, String> queryStrings;
public ProductRequest(ProductDocumentGeneratorFactory DocumentGeneratorFactory,HashMap<String, String> queryStrings){
this.DocumentGeneratorFactory = DocumentGeneratorFactory;
this.queryStrings = queryStrings;
}
@Override
void prepareRequest() throws ParserConfigurationException, SAXException, IOException {
doc = this.DocumentGeneratorFactory.createDocument("http", "ip-address", "default.aspx",this.queryStrings);
}
}