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

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

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值