这取决于你的 XML 文件结构。如果我可以单独访问 A/B/C/...,我的 c++/boost 代码将如下所示。
重构类 FunctionalityA 中所有与 A 相关的东西,类 FunctionalityB 中与 B 相关的东西,... FunctionalityProvider 类是您配置系统功能的类。TheOneAndOnlyMethod 向提供者询问所有功能并对其进行迭代。
class XmlFunctionality
{
public:
virtual ~XmlFunctionality(){
}
virtual void loadFromConfig(XmlBasedConfig) = 0;
virtual bool isEnabled() const = 0;
virtual void execute() = 0;
protected:
XmlFunctionality(){
};
}
class FunctionalityA : public XmlFunctionality
{
public:
void loadFromConfig(XmlBasedConfig){
// load A information from xml
}
bool isEnabled() const{
return globalA.length()>0; // is A a global !?
}
void execute(){
// do you're a related stuff
}
}
class FunctionalityB : public XmlFunctionality
{
public:
void loadFromConfig(XmlBasedConfig){
// load B information from xml
}
bool isEnabled() const{
// when is b enabled ...
}
void execute(){
// do you're b related stuff
}
}
// Map your question to the functions -
class FunctionalityProvider
{
Functionality functionalityList;
public:
typedef std::vector<XmlFunctionality*> Functionality;
FunctionalityProvider() : functionalityList() {
functionalityList.push_back( new FunctionalityA);
functionalityList.push_back( new FunctionalityB);
functionalityList.push_back( ... );
}
~FunctionalityProvider {
for_each( functionality.begin(), functionality.end(), delete_ptr() );
}
Functionality functionality() const {
return functionalityList;
}
}
void TheOneAndOnlyMethod(XmlBasedConfig config, const FunctionalityProvider& provider) {
const FunctionalityProvider::Functionality functionality = provider.functionality();
for_each(
functionality.begin(),
functionality.end(),
bind(&XmlFunctionality::loadFromConfig, _1, config)); // or some other way of parsing the file
for_each(
functionality.begin(),
functionality.end(),
if_then( bind(&XmlFunctionality::isEnabled, _1), bind(&XmlFunctionality::execute, _1)));
}
如果我不能单独访问 A/B/C,我会让解析器根据 XML 文件的内容返回功能列表。