我创建了一个实现常用方法的抽象类 A。现在我意识到一个新类必须使用相同的方法但具有不同的属性值。下面是一个快速的总结:
public abstract class A implement IUtils {
protected final String LOGIN_XPATH = "xpathA";
public String getLoginName() {
return getXpath(LOGIN_XPATH);
}
}
public class B extends A {
private final String LOGIN_XPATH = "xpathB";
}
调用 B.getXpath() 将导致调用超级方法,因此使用“xpathA”。我希望它使用“xpathB”。我考虑在 A 类中使用以下组合:
public abstract class A implement IUtils {
protected IXpaths xpaths = null;
public A() {
xpaths = new XPathsClass();
}
public String getLoginName() {
return getXpath(xpaths.getXpath(StaticString.LOGIN_XPATH));
}
}
public class StaticString {
public final String LOGIN_XPATH = "LOGIN_XPATH";
}
public class XPathsClass implements IXpaths {
private static final Map<String, String> conversionMap = new HashMap<String, String>();
static {
conversionMap.put(StaticString.LOGIN_XPATH, "xpathA");
}
public String getValue(String query) {
return conversionMap.get(query);
}
}
public class XPathsClassB implements IXpaths {
private static final Map<String, String> conversionMap = new HashMap<String, String>();
static {
conversionMap.put(StaticString.LOGIN_XPATH, "xpathB");
}
public String getValue(String query) {
return conversionMap.get(query);
}
}
public class B extends A {
public B() {
super();
xpaths = new XPathsClassB();
}
}
这似乎有效,但它使它变得很长并且更难以阅读。有什么更好的方法?