C++实现的composite pattern(组合模式)

来源:互联网 发布:万网单域名控制台 编辑:程序博客网 时间:2024/06/15 00:02

最近被设计模式深深吸引,记录自己经历和实验,以备以后翻阅:

1. 设计模式名称:composite pattern

2. 设计模式解决的问题: 解决整体和部分关系,尤其适合递归式整体和部分关系。如树结构,家具结构或者电脑硬件结构等等。

3. 设计模式的设计思想:设计一个接口,它公布所有或者部分子类操作。让用户程序无差别对待子类(原子子类和组合子类)。该模式有两种方法实现:

     a: 处于安全考虑,只有所有子类都意义操作放在公共接口中,而组合子类独有方法放在子类中。这样设计将减弱了多态性,或者说透明性。

     b: 处于多态性或者透明性考虑,把所有的子类操作都放在公共接口中,而每个子类实现自己关心的接口。设计模式书本推荐不允许某操作的子类

           实现成抛出异常。

4.  设计模式的参与者:客户程序,公共接口,诸多子类

5.  设计模式图:略

6.  设计模式实例: C++ 版本 二叉树


#include <iostream>
#include <exception>


using namespace std;


class Node
{
public:
Node(int i):_i(i)
{
}
virtual ~Node(){}
int getI(){return _i;}


virtual int getLength()
{
return 0;
};


virtual void addLeaf(Node* l, Node* r)
{
//throw;
}


protected:
int _i;
};


class Leaf: public Node
{
public:
Leaf(int i):Node(i)
{
}


int getLength()
{
return 1;
}


void addLeaf(Node* l, Node* r)
{
throw ;
}
};
class InterNode: public Node
{
public:
InterNode(int i):Node(i)
{
_left=nullptr;
_right=nullptr;
}


int getLength()
{
if(this->_left == nullptr && this->_right == nullptr)
{
return 1;
}
else
{
if(this->_left == nullptr)
{
return this->_right->getLength()+1;
}
else if(this->_right == nullptr)
{
return this->_left->getLength()+1;
}
else if(this->_left->getLength()>this->_right->getLength())
{
return (this->_left->getLength()+1);
}
else
{
return (this->_right->getLength()+1);
}


}


}


void addLeaf(Node* l, Node* r)
{
_left=l;
_right=r;
}
private:
Node* _left;
Node* _right;


};


int main()
{
Node* root=new InterNode(100);
Node* node1=new InterNode(10);
Node* node2=new InterNode(10);

root->addLeaf(node1, node2);

Node* node3=new InterNode(10);
Node* node4=new InterNode(100);

Node* rleaf=new Leaf(120);

Node* lleaf=new Leaf(110);
lleaf->addLeaf(nullptr, nullptr);

node4->addLeaf(lleaf, nullptr);
node3->addLeaf(node4,rleaf);

node2->addLeaf(nullptr, node3);

cout<<root->getLength()<<endl;
delete root;
delete node1;
delete node2;
delete node3;
delete node4;
delete rleaf;
delete lleaf;
return 0;
}

原创粉丝点击