类包装设计问题

时间:2010-10-20 16:09:23

标签: c++ wrapper

我想在我的项目中的一些自定义类中包含部分TinyXML库,因为我只需要它的一些功能而且我不希望暴露所有内容。

我遇到一个问题,我的XMLDocument::AddNode(...)函数基本上与我的XMLNode类的作用相同。我想知道是否有人可以给我一些关于如何包装TinyXML库的设计技巧,所以我不打破封装,我的包装类不会将TinyXML库暴露给我的其余代码。

class XMLNode
    {
    public:
        XMLNode::XMLNode();
        XMLNode::XMLNode(const std::string& element);  // Creates a TiXMLElement object
        XMLNode::XMLNode(XMLNode& nodycopy);
        XMLNode::~XMLNode();

        XMLNode GetFirstChild();
        XMLNode GetNextSibling();

        std::string GetNodeValue();
        std::string GetNodeName();

        void AddNodeText(const std::string& text);
        void AddNodeAttribute();

    private:
        std::string value;
        std::string nodename;

        TiXmlElement* thisnode;
    };

//These functions do the same as my AddNode does from XMLDocument, it seems rather silly...
    XMLNode::XMLNode(const std::string& str_element) 
{
    thisnode = new TiXmlElement(str_element.c_str());
    nodename = str_element;
}

void XMLNode::AddNodeText(const std::string& nodetext)
{
    TiXmlText* text = new TiXmlText(nodetext.c_str());
    thisnode->LinkEndChild(text);
    value = nodetext;
}


class XMLDocument
    {
    public:
        XMLDocument::XMLDocument(const std::string& documentname);
        XMLDocument::~XMLDocument();

        void SaveToFile(std::string filename);
        std::string basicXML(std::string rootnode);

        void AddNode(XMLNode& node);
        XMLNode GetXPathNode(const std::string& node);
        void AppendCloneNodeAsChild(XMLNode& nodetoappend); 

        void SetRoot(XMLNode& rootnode);
    private:
        TiXmlDocument document;
        TiXmlElement root;
        TiXmlElement currentelement;

    };

void XMLDocument::AddNode(XMLNode& node)  // This function does over what XMLNode class is actually for... I just want to add the node to the XMLDocument
{
    std::string val = node.GetNodeName();
    TiXmlElement* el = new TiXmlElement(val.c_str());
    TiXmlText * txt = new TiXmlText(node.GetNodeValue().c_str());
    el->LinkEndChild(txt);
    document.LinkEndChild(el);
}

有人可以给我一些关于如何正确包装这个并且只展示我想要的TinyXML功能的建议吗?

2 个答案:

答案 0 :(得分:1)

您已经封装了TinyXml document - 现在您只需要在其中委托它,只显示它提供的函数的子集。

替换此

void XMLDocument::AddNode(XMLNode& node)  // This function does over what XMLNode class is actually for... I just want to add the node to the XMLDocument
{
    std::string val = node.GetNodeName();
    TiXmlElement* el = new TiXmlElement(val.c_str());
    TiXmlText * txt = new TiXmlText(node.GetNodeValue().c_str());
    el->LinkEndChild(txt);
    document.LinkEndChild(el);
}

用这个

void XMLDocument::AddNode(XMLNode& node) 
{
    document.AddNode(node);
}

这是完全合法的,因为您不希望将完整的TiXmlDocument公开给您班级的客户。想一想std::queuestd::stack如何充当底层容器上的适配器。

答案 1 :(得分:0)

有两种方法可以解决这个问题。

  1. 从XMLDocument派生
  2. 拥有XMLDocument的对象并将调用转发给它。