51,390
社区成员




abstract class Person{
abstract String getGender();
}
class Femal extends Person{
String getGender(){
return "femal";
}
}
class Male extends Person{
String getGender(){
return "male";
}
}
<prices>
<price code="1" classname="com.test.RegularPrice" />
<price code="2" classname="com.test.ChildrensPrice" />
<price code="3" classname="com.test.NewReleasePrice" />
</prices>
import java.util.HashMap;
import java.util.Map;
public class PriceConfig {
private int code;
private Class<Price> clazz;
private static Map<Integer, PriceConfig> map = new HashMap<Integer, PriceConfig>();
PriceConfig(int code, String classname) {
this.code = code;
this.clazz = initClass(classname);
register(this);
}
@SuppressWarnings("unchecked")
private Class<Price> initClass(String classname) {
Class<Price> clazz = null;
try {
clazz = (Class<Price>)Class.forName(classname);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(classname + " isnot exist");
}
if(!clazz.isAssignableFrom(Price.class)) {
throw new IllegalArgumentException(classname + " isnot Price implementation");
}
return clazz;
}
private static void register(PriceConfig priceConfig) {
map.put(priceConfig.getCode(), priceConfig);
}
public static Price getPrice(int code) {
PriceConfig price = map.get(code);
if(price == null) {
new IllegalArgumentException("Incorrect Price Code");
}
return price.getPrice();
}
public int getCode() {
return code;
}
public Class<Price> getClassname() {
return clazz;
}
public Price getPrice() {
try {
return (Price)clazz.newInstance();
} catch (InstantiationException e) {
throw new Xxxxxxxxx();
} catch (IllegalAccessException e) {
throw new Xxxxxxxxx();
}
}
}