Android SDK开发
U8SDK采用插件式的设计模式,将用户相关的功能定义为一个User插件;当支付相关的功能定义为一个Pay插件。具体的类代表分别是IUser接口和IPay接口。
所以,在接入具体的SDK时,我们需要实现这两个插件。对应的,我们就必须定义一个XUser和XPay来分别实现IUser和IPay接口
使用xml配置文件的方式,通过固定key查找到相应的插件值values,如:com.u8.sdk.BaiduUser
最后通过反射的方式实例化插件的实现类。达到使用插件化的方式使用百度SDK替换空壳SDK的具体实现
demo
PluginFactory
核心思想利用Java的反射原理实现插件式的设计模式
public Object initPlugin(int type){
Class localClass = null;
try {
if(!isSupportPlugin(type)){
if(type == IUser.PLUGIN_TYPE || type == IPay.PLUGIN_TYPE){
Log.e("U8SDK", "The config of the U8SDK is not support plugin type:"+type);
}else{
Log.w("U8SDK", "The config of the U8SDK is not support plugin type:"+type);
}
return null;
}
String pluginName = getPluginName(type);
localClass = Class.forName(pluginName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
try {
return localClass.getDeclaredConstructor(new Class[]{Activity.class}).newInstance(new Object[]{U8SDK.getInstance().getContext()});
} catch (Exception e) {
try {
//以默认构造函数再次尝试实例化
return localClass.getDeclaredConstructor().newInstance();
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return null;
}